reactjs输入选择选项无法添加

时间:2017-10-11 02:23:14

标签: javascript reactjs core-ui

您好我正在尝试从后端获取选项列表,然后将它们映射到选项列表并添加到列表但失败了。请问有人可以提供建议吗?

父组件:

fetch(urlMakerNames)
.then((response) => response.json())
.then((responseJson) => {
    var array = JSON.parse(responseJson.marker_names);
    var options = array.map((opt, index) => {
        console.log('opt = ' + opt + ', index = ' + index);
        return '<option key="' + index + '" value="' + opt + '">' + opt + '</option>';
    });

    console.log('BEFORE options = ' + options + ', markerNames = ' + this.state.markerNames);

    this.setState({
        markerNames: options
    });

    console.log('AFTER options = ' + options + ', markerNames = ' + this.state.markerNames);

}).catch((error) => {
    console.error("MarkerForm error = " + error);
});

子组件:

console.log('this.props.markerNames = ' + this.props.markerNames);
<FormGroup>
    <Input type="select" name="markerName" onChange={this.props.handleInputChange} disabled={this.props.isViewMode} required>
        <option key="12345" value="TEST">TEST</option>
        {this.props.markerNames}
    </Input>
</FormGroup>

日志显示:

opt = zzz, index = 0
BEFORE options = <option key="0" value="zzz">zzz</option>, markerNames = 
this.props.markerNames = <option key="0" value="zzz">zzz</option>
AFTER options = <option key="0" value="zzz">zzz</option>, markerNames = <option key="0" value="zzz">zzz</option>

从log中可以看出,markerNames以正确的格式传递给子组件,匹配<option key="12345" value="TEST">TEST</option>但在输入选择元素中只能看到TEST选项但是zzz消失了。

2 个答案:

答案 0 :(得分:1)

获得阵列后,无需手动创建元素。通过在渲染函数中映射数组本身,将您的状态用作JSX元素的源。

请改为尝试:

fetch(urlMakerNames)
.then((response) => response.json())
.then((responseJson) => {
    var array = JSON.parse(responseJson.marker_names);

    this.setState({
        markerNames: array
    });

}).catch((error) => {
    console.error("MarkerForm error = " + error);
});



    <FormGroup>
        <Input type="select" name="markerName" onChange={this.props.handleInputChange} disabled={this.props.isViewMode} required>
            {this.props.markerNames.map((option, inx)=>{
              return <option key={inx} value={option}>{option}</option>;
            })}
        </Input>
    </FormGroup>

答案 1 :(得分:0)

您在这里返回一个字符串而不是反应组件

return '<option key="' + index + '" value="' + opt + '">' + opt + '</option>';

尝试

return <option key={index} value={opt}>{opt}</option>;

这将返回将在Input jsx中呈现的react组件。

相关问题