react in a form using AntD
1. The two-way data binding
render() {
const { getFieldDecorator } = this.props.form;//双向数据绑定
return (
<div>
<Form >
<FormItem label="姓名">
{getFieldDecorator('userName')(
<Input></Input>
)}
</FormItem>
</Form>
</div>
);
}
important point
- We will complain directly, use Form.create (options) to accept the data
and finally add the following code to the js file
form = Form.create({})(form);
export default form
- Set the initial value of the time
Can not be used directly in the form in value=
, this will error:
Warning: getFieldDecorator
will override value
, so please don’t set value
directly and use setFieldsValue
to set it.
InitalValue need to set the required values of getFieldDecorator
<Form.Item key={i} >
{getFieldDecorator(field,{
initialValue:item.initLabel,//设置的默认值
})(
<Select
style={{ width: '120' }}
onChange={this.handleCurrencyChange}
>
{BaseUI.getOptionList(item.Options)}
</Select>
)}
</Form.Item>
2. Get form data
Here is detached to form separate components userForm an example
we introduce userForm components in other pages
<UserForm wrappedComponentRef={(form) => this.userForm = form}>
</UserForm>
wrappedComponentRef
Vue equivalent to the ref, so this.userform
that the dom node
- retrieve data
this.userForm.props.form.getFieldsValue()
- Data Reset
this.userForm.props.resetFields()
Please refer to the document antd
3. Form Validation
Basic usage
<Form.Item key="author">
{getFieldDecorator("author", { rules: [{ required: true, message: '请输入作者!' }] })
(<Input placeholder="作者" allowClear />)}
</Form.Item>
Custom validation
checkPhone = (rule, value, callback) => {
let reg = /^1(3|4|5|7|8)\d{9}$/;
if (!value) {
callback("请输入手机号")
}
else if (!reg.test(value)) { callback("请输入正确的手机号格式") }
else {
callback()
}
}
...
<Form.Item key="phone">
{getFieldDecorator("phone", { rules: [{ validator: this.checkPhone }], })
(<Input placeholder="手机号" allowClear />)}
</Form.Item>