zoukankan      html  css  js  c++  java
  • 手写实现简版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);
  • 相关阅读:
    python,selenium遇到的问题
    python环境配置
    性能测试函数
    性能测试的关注点
    环境配置
    性能监控工具使用
    linux路径
    linux权限
    自动化测试工具
    书籍
  • 原文地址:https://www.cnblogs.com/flamestudio/p/12625066.html
Copyright © 2011-2022 走看看