React + Form + getFieldDecorator + setFieldsValue

getFieldDecorator

class Form extends Component {
    state = {
        createInput: '',
    }
    handleSubmit = e => {
        e.preventDefault() 
        this.props.form.validateFields({ force: true }, (err, values) => {
            if (!err) {
                this.setState(
                    {
                        createInput: values.ApiName//给input等内容赋值
                    }
                )
            }
        })
    } 
    render() {
        const { theme } = this.props 
        const { getFieldDecorator } = this.props.form
        return (
            <div>
                <h4 className={`createTitle`}>标题</h4>
                <div className={`createBox`}>
                    <Form layout="horizontal" onSubmit={this.handleSubmit}>
                        <Item>
                            {getFieldDecorator('ApiName', {
                                initialValue: this.state.createInput,//设置默认value 
                                rules: [
                                    {
                                        required: true,//是否为必填项
                                        whitespace: true,//是否匹配空格
                                        pattern: new RegExp(/^[a-zA-Z0-9\u4e00-\u9fa5]{2,10}$/),//要匹配等正则
                                        message: "( 2-10个字符,不能包含特殊字符 )",//输入不合法要提示等信息
                                    },
                                ],
                                validateTrigger: 'onBlur',
                            })(
                                <Input
                                    autoComplete="off"
                                    className={`createNameInput`}
                                    placeholder={ "( 2-10个字符,不能包含特殊字符 )"}
                                    maxLength={10}
                                />
                            )}
                        </Item>
                        <Item>
                            <Button type="primary" htmlType="submit"> 创建 </Button>
                        </Item>
                    </Form> 
                </div>
            </div>
        )
    }
}

export default Form.create({})(Form)

#setFieldsValue

class Index extends Component{
	constructor(props) {
        super(props)
        this.state = { }
    }
    // example 为Form.Item中的name
componentDidMount () {
	this.formRef.current.setFieldsValue({
       example: ‘从后台返回要显示的值’,				
	})
}
    // 创建一个ref
    formRef = React.createRef()
    render(){
    	return{
    	     {/* 绑定到Form身上*/}
        	 <Form ref={this.formRef}>
                <Form.Item name="example">
                   <Input />
                </Form.Item>
             </Form>
        }
    }
}


export default BaseInfo

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值