React Js从数组创建选项列表

Bom*_*ber 1 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>      
        );
}
Run Code Online (Sandbox Code Playgroud)

数据:

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}
    ];
Run Code Online (Sandbox Code Playgroud)

我一直收到错误:

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

有人可以帮忙吗?

jur*_*six 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>
});
Run Code Online (Sandbox Code Playgroud)

  • 这是正确答案,但我建议添加一个解释.如果你这样做我会赞成你:) (2认同)