【问题标题】:reactjs input select options cannot be addedreactjs输入选择选项无法添加
【发布时间】:2017-10-11 02:23:14
【问题描述】:

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

父组件:

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>

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

【问题讨论】:

  • FormGroup?是任何库的一部分吗?

标签: javascript reactjs core-ui


【解决方案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>

【讨论】:

    【解决方案2】:

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

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

    试试

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

    这将返回将在您的 Input jsx 中呈现的反应组件。

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 2013-06-29
      • 2021-09-02
      • 1970-01-01
      • 2020-07-11
      • 2018-07-02
      • 1970-01-01
      • 2020-04-29
      • 2022-09-23
      相关资源
      最近更新 更多