react 之getFieldDecorator用法


react ant Design組件官網地址:
https://ant.design/components/form-cn/#header


今天來講下 getFieldDecorator 方法

   **登陸注冊表單制作時,除了可以引入UI樣式,Ant Design 也提供了JS屬性對象。**

// 獲取 getFieldDecorator JS屬性對象,這個值的作用是幫助我們做表單封裝 const { getFieldDecorator } = this.props.form; <From> <FormItem> //JS屬性對象書寫時需要用 { } 包裹起來,不能直接寫在代碼塊中 { getFieldDecorator('userName',{ initialValue:'Jack', rules:[] })( <Input placeholder='請輸入用戶名'/> ) } </FormItem> </From>

如下圖:

getFieldDecorator是一個方法,這個方法接收兩個參數,第一個是表單的字段對象,
第二個是驗證規則。這個方法本身返回一個方法,需要將需要獲取值的標簽包裹進去

` 如果此時報錯:
TypeError: Cannot read property 'getFieldDecorator' of undefined

就證明沒有導出,需要在頁面最后面加上下面這句代碼:
export default Form.create()(FormLogin)

這句話非常重要,表明我們是通過 Form.create()方法創建了具備getFieldDecorator功能的這個表單FormLogin,這樣才能通過this.props.form調用。

同時將最上方的 export default class FormLogin extends React.Component{  }
中的  export default  去掉,只保留下方的即可.`

或者直接引用:
`

import { Button,Radio, Form, Row, Col,message,Modal } from "antd";
const FormItem = Form.Item;

//在render  里面  寫上
   const { getFieldsValue,getFieldDecorator } = this.props.form;

  return (
            <div className={styles.question} key={item.directoryIndexTableId}>
                <div className={styles.questionT}>
                    {item.order}.{item.evaluationIndexName} <span className={styles.primary}>【單選題】</span>
                </div>
                {getFieldDecorator(`${item.directoryIndexTableId}`, {
                    initialValue: item.initData ? this.onChange1(item,item.initData,'init') : undefined,
                    rules: [{ required: true, message: '請選擇!' }]
                })(
                    <RadioGroup   onChange={(e)=>this.onChange1( item, e.target.value,'change')}>
                        {item.evaluationRankOptionVos.map((x, i) => {
                            return (
                                <div key={i} className={styles.radioItem}>
                                    <Radio  value={x.rankOptionId} >{x.rankOptionName}</Radio>
                                </div>
                            );
                        })}
                    </RadioGroup>
                )}
            </div>
        );


`

getFieldDecorator 方法的第一個參數 可以是具體的字符串,用 "" 即可,
也可已是 動態的, 動態的賦值方式可以是: 斜點符號${item.directoryIndexTableId}斜點符號 ,如上代碼,記得用 斜點符號括起來。


免責聲明!

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



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