首页 > 解决方案 > ReactJs - 迭代对象以创建表单字段

问题描述

我决定迭代一个数组并创建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}

有什么建议吗?

标签: javascriptreactjssemantic-ui

解决方案


在您的情况下,state声明为 aclass properties而不是 a 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.

推荐阅读