HeavenTang

导航

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}斜点符号 ,如上代码,记得用 斜点符号括起来。

posted on 2020-06-03 21:10  HeavenTang  阅读(14290)  评论(0编辑  收藏  举报