Antd@3.x和Antd@4.x有些地方區別還是挺大的。
Form表單的一個常規寫法:
1.通過 Form.useForm 對表單數據域進行交互。
const [form] = Form.useForm();
//這里用form要使用在鈎子函數里,可以配合react的hook使用,
如果使用react生命周期開發的話可以給form表單添加ref來獲取表單數據或者修改數據,(this.formRef = React.createRef();)
獲取表單數據:this.formRef.current.getFieldsValue()。this.formRef.current.validateFields().then().catch()
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const validateMessages = {
required: '${label} is required!',
types: {
email: '${label} is not a valid email!',
number: '${label} is not a valid number!',
},
number: {
range: '${label} must be between ${min} and ${max}',
},
};
<Form form={form} {...layout} name="nest-messages" onFinish={onFinish.bind(this)} validateMessages={validateMessages} className="login-form"
initialValues={{ name: 'ming', password: '123456' }}
>
<Form.Item name='name' label="用戶名" rules={[{ required: true }]}>
<Input placeholder="用戶名" />
</Form.Item>
<Form.Item name='password' label="密碼" rules={[{ required: true }]}>
<Input placeholder="用戶密碼" />
</Form.Item>
<Form.Item >
<Button type="primary" htmlType="submit" className="login-form-button">
登錄
</Button>
<Button >重置表單</Button>
</Form.Item>
</Form>
2.獲取對應字段名的值。用法:
form.getFieldValue('name');
form.getFieldValue('password')
3.設置表單的值,更新對應的值,用法:
form.setFieldsValue({
name: 'ming',
password: '111222'
});
4.獲取Form全部字段名對應的值,會按照對應結構返回。用法:
form.getFieldsValue()
5.觸發表單驗證。用法:
form.validateFields().then(value => {
6.提交表單,與點擊 submit 按鈕效果相同,會走 onFinish 方法。用法:
<Button onClick={() => form.submit()}> 提交 </Button>
7.重置一組字段到 initialValues。用法:
form.resetFields();
8.獲取光標方法:
form.getFieldInstance('name').focus();