在 react 中 由於沒有數據雙向綁定,在 使用表單的時候,就需要自己一個一個的綁定,獲取值的時候,也去要一個一個的去狀態里面拿值,想在點擊提交按鈕 把表單中的所以=有數據獲取到,
一般都是 使用 antd 中的 Form 組件,這樣確實很方便,但是 如果 是自定義組件的時候就會有問題,出現 取不到值,或者,編輯表單的時候 值不能回顯,需要手動單個處理,還是很不方便的,
下面記錄的就是處理 自定義組件的方式。
父組件:
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> ); } }
子組件:
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 的方式 設置表單值,也是可以得到值 進行顯示,在編輯回顯數據 很有用的
rc-form
在我們 用不了 antd 中的 Form 組件 或者 不需要用的時候,但是 還是想用表單一鍵取值的時候,可以用這個庫。antd 中Form 組件也是使用這個庫的
使用方式如下
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);
自定義組件的方式仍然是一樣的