Antd@4.x Form的常用方法


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 => { 

// 驗證通過后進入 const { name,password} = value; console.log(name, password);

}).catch(err => { // 驗證不通過時進入 console.log(err); });
6.提交表單,與點擊 submit 按鈕效果相同,會走 onFinish 方法。用法:
<Button onClick={() => form.submit()}> 提交 </Button> // 與下面效果一樣 <Button htmlType="submit"> 提交 </Button>

7.重置一組字段到 initialValues。用法:
form.resetFields();

8.獲取光標方法:
form.getFieldInstance('name').focus();





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM