├── public
├── favicon.ico
├── logo192.png
├── logo512.png
├── robots.txt
├── manifest.json
└── index.html
├── src
├── components
│ ├── my-rc-field-form
│ │ ├── FieldContext.js
│ │ ├── index.js
│ │ ├── Form.js
│ │ ├── Field.js
│ │ └── useForm.js
│ └── Input.js
├── index.js
├── App.js
├── index.less
└── pages
│ ├── MyRCFieldForm.js
│ └── AntdFormPage.js
├── .gitignore
├── craco.config.js
├── package.json
└── README.md
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bubucuo/form-nut/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bubucuo/form-nut/HEAD/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bubucuo/form-nut/HEAD/public/logo512.png
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/components/my-rc-field-form/FieldContext.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | const FieldContext = React.createContext();
4 |
5 | export default FieldContext;
6 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import {createRoot} from "react-dom/client";
2 |
3 | import "./index.less";
4 | import App from "./App";
5 |
6 | const root = createRoot(document.getElementById("root")).render();
7 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | // import AntdFormPage from "./pages/AntdFormPage";
2 | import MyRCFieldForm from "./pages/MyRCFieldForm";
3 |
4 | export default function App(props) {
5 | return (
6 |
10 | );
11 | }
12 |
--------------------------------------------------------------------------------
/src/components/my-rc-field-form/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import _Form from "./Form";
3 | import Field from "./Field";
4 | import useForm from "./useForm";
5 |
6 | const Form = React.forwardRef(_Form); //_Form;
7 |
8 | Form.Field = Field;
9 | Form.useForm = useForm;
10 |
11 | export { Field, useForm };
12 | export default Form;
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/craco.config.js:
--------------------------------------------------------------------------------
1 | // * 配置完成后记得重启下
2 | const CracoLessPlugin = require("craco-less");
3 |
4 | module.exports = {
5 | babel: {
6 | //用来支持装饰器
7 | plugins: [["@babel/plugin-proposal-decorators", {legacy: true}]]
8 | },
9 | plugins: [
10 | {
11 | plugin: CracoLessPlugin,
12 | options: {
13 | lessLoaderOptions: {
14 | lessOptions: {
15 | modifyVars: {
16 | "@primary-color": "red",
17 | "@border-color-base": "green",
18 | "@link-color": "orange"
19 | },
20 | javascriptEnabled: true
21 | }
22 | }
23 | }
24 | }
25 | ]
26 | };
27 |
--------------------------------------------------------------------------------
/src/components/my-rc-field-form/Form.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import FieldContext from "./FieldContext";
3 | import useForm from "./useForm";
4 |
5 | export default function Form(
6 | { children, form, onFinish, onFinishFailed },
7 | ref
8 | ) {
9 | const [formInstance] = useForm(form);
10 |
11 | React.useImperativeHandle(ref, () => formInstance);
12 |
13 | formInstance.setCallbacks({
14 | onFinish,
15 | onFinishFailed,
16 | });
17 | return (
18 |
28 | );
29 | }
30 |
--------------------------------------------------------------------------------
/src/index.less:
--------------------------------------------------------------------------------
1 | @import "~antd/dist/antd.less";
2 |
3 | body {
4 | /* margin: 0; */
5 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
6 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
7 | sans-serif;
8 | -webkit-font-smoothing: antialiased;
9 | -moz-osx-font-smoothing: grayscale;
10 | }
11 |
12 | code {
13 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
14 | monospace;
15 | }
16 |
17 | #root {
18 | padding: 10px;
19 | }
20 |
21 | .border {
22 | margin: 10px;
23 | padding: 10px;
24 | border: solid 1px red;
25 | }
26 |
27 | .red {
28 | color: red;
29 | }
30 |
31 | .green {
32 | color: green;
33 | }
34 |
35 | .pink {
36 | color: pink;
37 | }
38 |
--------------------------------------------------------------------------------
/src/components/Input.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | const Input = (props) => {
4 | return ;
5 | };
6 |
7 | // const CustomizeInput = ({value = "", ...props}) => (
8 | //
9 | //
10 | //
11 | // );
12 |
13 | class CustomizeInput extends React.Component {
14 | constructor(props) {
15 | super(props);
16 | this.state = {};
17 | }
18 | render() {
19 | const {value = "", ...otherProps} = this.props;
20 | return (
21 |
22 |
23 |
24 | );
25 | }
26 | }
27 |
28 | export default CustomizeInput;
29 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "form-nut",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@babel/plugin-proposal-decorators": "^7.12.1",
7 | "@craco/craco": "^5.7.0",
8 | "@testing-library/jest-dom": "^5.11.4",
9 | "@testing-library/react": "^11.1.0",
10 | "@testing-library/user-event": "^12.1.10",
11 | "antd": "^4.7.3",
12 | "craco-less": "^1.17.0",
13 | "react": "^18.2.0",
14 | "react-dom": "^18.2.0",
15 | "react-scripts": "4.0.0",
16 | "web-vitals": "^0.2.4"
17 | },
18 | "scripts": {
19 | "start": "craco start",
20 | "build": "craco build",
21 | "test": "craco test"
22 | },
23 | "eslintConfig": {
24 | "extends": [
25 | "react-app",
26 | "react-app/jest"
27 | ]
28 | },
29 | "browserslist": {
30 | "production": [
31 | ">0.2%",
32 | "not dead",
33 | "not op_mini all"
34 | ],
35 | "development": [
36 | "last 1 chrome version",
37 | "last 1 firefox version",
38 | "last 1 safari version"
39 | ]
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/src/components/my-rc-field-form/Field.js:
--------------------------------------------------------------------------------
1 | import React, {Component} from "react";
2 | import FieldContext from "./FieldContext";
3 | // export default class Field extends Component {
4 | // static contextType = FieldContext;
5 |
6 | // componentDidMount() {
7 | // this.unregister = this.context.registerFieldEntities(this);
8 | // }
9 |
10 | // componentWillUnmount() {
11 | // this.unregister();
12 | // }
13 |
14 | // onStoreChange = () => {
15 | // this.forceUpdate();
16 | // };
17 |
18 | // getControlled = () => {
19 | // const { getFieldValue, setFieldsValue } = this.context;
20 | // const { name } = this.props;
21 | // return {
22 | // value: getFieldValue(name), //"omg", // get state
23 | // onChange: (e) => {
24 | // const newValue = e.target.value;
25 | // // set state
26 | // setFieldsValue({ [name]: newValue });
27 | // },
28 | // };
29 | // };
30 | // render() {
31 | // const { children } = this.props;
32 |
33 | // const returnChildNode = React.cloneElement(children, this.getControlled());
34 | // return returnChildNode;
35 | // }
36 | // }
37 |
38 | export default function Field(props) {
39 | const {children, name} = props;
40 |
41 | const {
42 | getFieldValue,
43 | setFieldsValue,
44 | registerFieldEntities,
45 | } = React.useContext(FieldContext);
46 |
47 | const [, forceUpdate] = React.useReducer((x) => x + 1, 0);
48 |
49 | React.useLayoutEffect(() => {
50 | const unregister = registerFieldEntities({
51 | props,
52 | onStoreChange: forceUpdate,
53 | });
54 | return unregister;
55 | }, []);
56 |
57 | const getControlled = () => {
58 | return {
59 | value: getFieldValue(name), //"omg", // get state
60 | onChange: (e) => {
61 | const newValue = e.target.value;
62 | // set state
63 | setFieldsValue({[name]: newValue});
64 | },
65 | };
66 | };
67 |
68 | const returnChildNode = React.cloneElement(children, getControlled());
69 | return returnChildNode;
70 | }
71 |
--------------------------------------------------------------------------------
/src/pages/MyRCFieldForm.js:
--------------------------------------------------------------------------------
1 | import React, { Component, useEffect } from "react";
2 | // import Form, { Field } from "rc-field-form";
3 | import Form, { Field } from "../components/my-rc-field-form/";
4 | import Input from "../components/Input";
5 |
6 | const nameRules = { required: true, message: "请输入姓名!" };
7 | const passworRules = { required: true, message: "请输入密码!" };
8 |
9 | // export default function MyRCFieldForm(props) {
10 | // const [form] = Form.useForm();
11 |
12 | // const onFinish = (val) => {
13 | // console.log("onFinish", val); //sy-log
14 | // };
15 |
16 | // // 表单校验失败执行
17 | // const onFinishFailed = (val) => {
18 | // console.log("onFinishFailed", val); //sy-log
19 | // };
20 |
21 | // useEffect(() => {
22 | // console.log("form", form); //sy-log
23 | // // form.setFieldsValue({ username: "default" });
24 | // }, []);
25 |
26 | // return (
27 | //
28 | //
MyRCFieldForm
29 | //
38 | //
39 | // );
40 | // }
41 |
42 | export default class MyRCFieldForm extends Component {
43 | formRef = React.createRef();
44 | componentDidMount() {
45 | console.log("form", this.formRef.current); //sy-log
46 | this.formRef.current.setFieldsValue({ username: "default" });
47 | }
48 |
49 | onFinish = (val) => {
50 | console.log("onFinish", val); //sy-log
51 | };
52 |
53 | // 表单校验失败执行
54 | onFinishFailed = (val) => {
55 | console.log("onFinishFailed", val); //sy-log
56 | };
57 | render() {
58 | return (
59 |
60 |
MyRCFieldForm
61 |
74 |
75 | );
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/pages/AntdFormPage.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, Component } from "react";
2 | import { Form, Button, Input } from "antd";
3 |
4 | const FormItem = Form.Item;
5 |
6 | const nameRules = { required: true, message: "请输入姓名!" };
7 | const passworRules = { required: true, message: "请输入密码!" };
8 |
9 | export default class AntdFormPage extends Component {
10 | formRef = React.createRef();
11 |
12 | componentDidMount() {
13 | this.formRef.current.setFieldsValue({ username: "defalut" });
14 | }
15 | onFinish = (val) => {
16 | console.log("onFinish", val); //sy-log
17 | };
18 | onFinishFailed = (val) => {
19 | console.log("onFinishFailed", val); //sy-log
20 | };
21 | render() {
22 | return (
23 |
24 |
AntdFormPage
25 |
42 |
43 | );
44 | }
45 | }
46 |
47 | // Antd 3 Form HOC
48 | // todo antd4 form store (state、)
49 |
50 | // export default function AntdFormPage(props) {
51 | // const [form] = Form.useForm();
52 | // const onFinish = (val) => {
53 | // console.log("onFinish", val); //sy-log
54 | // };
55 | // const onFinishFailed = (val) => {
56 | // console.log("onFinishFailed", val); //sy-log
57 | // };
58 |
59 | // useEffect(() => {
60 | // form.setFieldsValue({username: "defalut"});
61 | // console.log("form", form); //sy-log
62 | // }, []);
63 |
64 | // return (
65 | //
66 | //
AntdFormPage
67 | //
80 | //
81 | // );
82 | // }
83 |
--------------------------------------------------------------------------------
/src/components/my-rc-field-form/useForm.js:
--------------------------------------------------------------------------------
1 | // 定义状态管理库
2 |
3 | import { useRef } from "react";
4 |
5 | class FormStore {
6 | constructor() {
7 | this.store = {}; // 状态值: name: value
8 | this.fieldEntities = [];
9 |
10 | this.callbacks = {};
11 | }
12 |
13 | setCallbacks = (callbacks) => {
14 | this.callbacks = { ...this.callbacks, ...callbacks };
15 | };
16 |
17 | // 注册实例(forceUpdate)
18 | // 注册与取消注册
19 | // 订阅与取消订阅
20 | registerFieldEntities = (entity) => {
21 | this.fieldEntities.push(entity);
22 |
23 | return () => {
24 | this.fieldEntities = this.fieldEntities.filter((item) => item !== entity);
25 | delete this.store[entity.props.name];
26 | };
27 | };
28 |
29 | // get
30 | getFieldsValue = () => {
31 | return { ...this.store };
32 | };
33 |
34 | getFieldValue = (name) => {
35 | return this.store[name];
36 | };
37 |
38 | // set
39 | // password: 123
40 | setFieldsValue = (newStore) => {
41 | // 1. update store
42 | this.store = {
43 | ...this.store,
44 | ...newStore,
45 | };
46 | // 2. update Field
47 | this.fieldEntities.forEach((entity) => {
48 | Object.keys(newStore).forEach((k) => {
49 | if (k === entity.props.name) {
50 | entity.onStoreChange();
51 | }
52 | });
53 | });
54 | };
55 |
56 | validate = () => {
57 | let err = [];
58 | // todo 校验
59 | // 简版校验
60 |
61 | this.fieldEntities.forEach((entity) => {
62 | const { name, rules } = entity.props;
63 |
64 | const value = this.getFieldValue(name);
65 | let rule = rules[0];
66 |
67 | if (rule && rule.required && (value === undefined || value === "")) {
68 | err.push({ [name]: rule.message, value });
69 | }
70 | });
71 |
72 | return err;
73 | };
74 |
75 | submit = () => {
76 | console.log("submit"); //sy-log
77 |
78 | let err = this.validate();
79 | // 提交
80 | const { onFinish, onFinishFailed } = this.callbacks;
81 |
82 | if (err.length === 0) {
83 | // 校验通过
84 | onFinish(this.getFieldsValue());
85 | } else {
86 | // 校验不通过
87 | onFinishFailed(err, this.getFieldsValue());
88 | }
89 | };
90 |
91 | getForm = () => {
92 | return {
93 | getFieldsValue: this.getFieldsValue,
94 | getFieldValue: this.getFieldValue,
95 | setFieldsValue: this.setFieldsValue,
96 | registerFieldEntities: this.registerFieldEntities,
97 | submit: this.submit,
98 | setCallbacks: this.setCallbacks,
99 | };
100 | };
101 | }
102 |
103 | export default function useForm(form) {
104 | // 存值,在组件卸载之前指向的都是同一个值
105 | const formRef = useRef();
106 |
107 | if (!formRef.current) {
108 | if (form) {
109 | formRef.current = form;
110 | } else {
111 | const formStore = new FormStore();
112 | formRef.current = formStore.getForm();
113 | }
114 | }
115 | return [formRef.current];
116 | }
117 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `yarn start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.\
15 | You will also see any lint errors in the console.
16 |
17 | ### `yarn test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `yarn build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `yarn eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35 |
36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39 |
40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `yarn build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------