在 react 中 因爲沒有數據雙向綁定,在 使用表單的時候,就須要本身一個一個的綁定,獲取值的時候,也去要一個一個的去狀態裏面拿值,想在點擊提交按鈕 把表單中的因此=有數據獲取到,react
通常都是 使用 antd 中的 Form 組件,這樣確實很方便,可是 若是 是自定義組件的時候就會有問題,出現 取不到值,或者,編輯表單的時候 值不能回顯,須要手動單個處理,仍是很不方便的,antd
下面記錄的就是處理 自定義組件的方式。ui
父組件:this
class Parent extends React.Component{ constructor(props){ super(props); }// 提交表單 handleSubmit = () => { this.props.form.validateFields((err: any, values: any) => { if (err){ return; } console.log(values); }) } render() {const { getFieldDecorator, getFieldProps, setFieldsValue } = this.props.form; return ( <div> <Form> <Form.Item {...formLayout1}> { getFieldDecorator('name')( <Child /> ) } </Form.Item> </Form> </div> ); } }
子組件:spa
class Child extends React.Component{ constructor(props){ super(props) this.state = { } } render() { const { onChange, value } = this.props;// 有默認傳來的 chang事件,和 value值 const { getFieldProps, name } = this.props;return ( <div> <Input onChange={(e)=>onChange(e.target.value)} value={value}/> </div> ); } }
以上操做就能夠在表單中使用自定義組件,表單也能統一獲取值, 而且 即使不是 input 輸入框, 也能夠是一些 別的什麼彈出選擇組件,只要你拿到值後,把值給 onChange 方法,都是能夠統一獲取值的,而後會在 props 上獲得一個 value ,用來顯示,以及 form 經過 setFiledsvalue 的方式 設置表單值,也是能夠獲得值 進行顯示,在編輯回顯數據 頗有用的雙向綁定
import React, { Component } from 'react'; import { Button, Input } from 'antd'; import { createForm, formShape } from 'rc-form';
class Login extends Component{ constructor(props) { super(props); this.state = { loading: false, user: '', pwd: '' }; } static propTypes = { form: formShape,
}; componentDidMount() { this.props.form.setFieldsValue({ name: '124' }) } submit = () => { this.props.form.validateFields((error: any, values: any)=>{ console.log(values); }) } render() { const { loading } = this.state; const form:any = this.props.form; const {getFieldDecorator, getFieldError } = form;return ( <div>
<div> { getFieldDecorator('name',{ rules: [{ required: true, message: '名字不能爲空' }], })(<AJTextField/>) } {
// 錯誤信息獲取 getFieldError('name') } </div> <div> { getFieldDecorator('pwd',{ rules: [{ required: true, message: '密碼不能爲空' }] })(<Input type="password" placeholder="請輸入密碼"/>)
} </div> <div> <Button onClick={this.submit}>登 錄</Button> </div> </div> ); } } export default createForm()(Login);
自定義組件的方式仍然是同樣的code