React Js从数组创建选项列表

时间:2016-02-06 20:15:32

标签: reactjs

我正在尝试为我的选择列表创建一个选项:

getMarkOptions: function () {
    var options = this.props.renderProps;

    return options.map(function (mark, i) {
        return <option
            key={i}
            value={mark}>
            {mark}
        </option>
    });
},


render: function () {

    console.log('mark editor ' + this.props);

    var selectedMark = this.props.value,
        row = this.props.data,
        highlightCurrentDay = this.props.highlight ? 'edit-select__currentDay':'';
        return (            
            <select
                value={selectedMark}
                ref="selectMark"
                className={"edit-select form-control " + highlightCurrentDay}
                onChange={this.onChange}
            >
                {this.getMarkOptions()}
            </select>      
        );
}

数据:

var marks = [
        {"id": 1, "caption": "/", "code": "/", "meaning": "Present (AM)", "isStandardCode": true},
        {"id": 2, "caption": "\\", "code": "\\", "meaning": "Present (PM)", "isStandardCode": true},
        {"id": 3, "caption": "B", "code": "B", "meaning": "Educated off site", "isStandardCode": true},
        {"id": 4, "caption": "C", "code": "C", "meaning": "Other Authorised Circumstances", "isStandardCode": true},
        {"id": 5, "caption": "D", "code": "D", "meaning": "Dual registration", "isStandardCode": true}
    ];

我一直收到错误:

未处理拒绝不变违规:对象作为React子对象无效(找到:具有键{id,caption,code,含义,isStandardCode}的对象)。如果您要渲染子集合,请使用数组,或者使用React附加组件中的createFragment(object)包装对象。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:7)

不变量指出选项标签的子项是对象 - <option>{mark}</option> - 但应该是有效的子项,例如string,int,React Component等 - <option>{mark.meaning}</option>

尝试这样的事情:

return options.map(function (mark, i) {
    return <option
        key={mark.id}
        value={mark.code}>
        {mark.meaning}
    </option>
});