手写实现简版AntDesign的Form组件(v3版本)

import React, {useState} from 'react';

const createForm = Cmp => props => {
    const [formData, setFormData] = useState({})
    const rules = {}
    return (
        <div>
            <Cmp {...props}
                 getFieldDecorator={(name, options) => {
                     if (options.rules) {
                         rules[name] = [...options.rules]
                     }
                     return (formItem) => React.cloneElement(formItem, {
                         name,
                         value: formData[name] || '',
                         onChange: e => {
                             setFormData({...formData, [name]: e.target.value})
                         }
                     })
                 }}
                 getFieldValue={fieldName => formData[fieldName]}
                 getFieldsValue={() => ({...formData})}
                 validateFields={cb => {
                     const err = []
                     Object.keys(rules).forEach(key => {
                         rules[key].forEach(rule => {
                             if (rule['required'] === true && (!formData[key] || formData[key].trim() === '')) {
                                 err.push(rule['message'] || (key + '为必填项!'))
                             }
                         })
                     })
                     cb(err.length ? err : undefined, formData)
                 }}
            />
        </div>
    )
}

function Form(props) {
    return (
        <div>
            {
                props.getFieldDecorator('name', {rules: [{'required': true, 'message': '用户名为必填项!'}]})(<input
                    type="text"/>)

            }
            {
                props.getFieldDecorator('password', {rules: [{'required': true, 'message': '密码为必填项!'}]})(<input
                    type="password" name="" id=""/>)
            }

            <button onClick={() => {
                props.validateFields((err, values) => {
                    if (err) {
                        console.log('验证失败', err)
                    } else {
                        console.log('验证通过', values)
                    }
                })
            }}>提交
            </button>
        </div>
    )

}

export default createForm(Form);

 

上一篇:go静态检查_安全检查


下一篇:easyrule规则引擎源码解析