ReactJs-遍历对象以创建表单字段

时间:2018-08-01 06:48:39

标签: javascript reactjs semantic-ui

我决定遍历一个数组并创建Form.Field(semantic-ui)。这是我的静态代码,就像一个魅力:

export default class OrderChange extends Component<Props> {
    constructor() {
        super();
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    state = {}
    handleChange = (e, { value }) => this.setState({ value })
     render() {
                  <Form.Field>
                    <Radio
                      label='A'
                      name='radioGroup'
                      value='this'
                      checked={this.state.value === 'this'}
                      onChange={this.handleChange}
                    />
                  </Form.Field>
                  <Form.Field>
                    <Radio
                      label='B'
                      name='radioGroup'
                      value='this1'
                      checked={this.state.value === 'this1'}
                      onChange={this.handleChange}
                    />
                  </Form.Field>

    });

我正在努力创建动态数据。首先,我创建了一个像这样的对象:

    const radios = [
        {
            name:'j',
            value:1
        },
        {
            name:'k',
            value:2
        }
    ];

然后,我尝试对其进行迭代:

                {radios.map(function (radio, index) {
                    return (
                        <Form.Field>
                            <Radio
                                label={radio.name}
                                name='radioGroup'
                                value='this'
                                checked={this.state.value === radio.value}
                                onChange={this.handleChange}
                            />
                        </Form.Field>
                    );
                })}

但是,我遇到了这个错误:

Cannot read property 'state' of undefined

在此行:

 checked={this.state.value === radio.value}

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

在您的情况下,state声明为class properties,而不是instance property

 state = {} //class property will not available on this object

在构造函数中进行state声明

constructor() {
  this.state = {};   // now state available on this object
}

checked={this.state.value === radio.value}将起作用

或从此处删除this

checked={state.value === radio.value} // with class property state,it will work.

答案 1 :(得分:0)

我认为最好使用() -> new RuntimeException("test")对象在构造函数中声明状态以访问状态

this