React,无法选择<select>的第一个选项

Vad*_*dea 3 select jsx reactjs react-jsx

<select>从一个数组中渲染一个盒子。我的数组如下所示:

options: [
    {"id":1,"name":"Option1"},
    {"id":2,"name":"Option2"},
    {"id":3,"name":"Option3"}
    ];
Run Code Online (Sandbox Code Playgroud)

map在数组中找到所有选项,然后在map. 但是,我可以从选择中选择任何选项,第一个除外。

这是我的选择:

<select
    className="form-control"
    name={this.props.name}
    onChange={this.handleChange.bind(this)}>
    {(Array.isArray(this.props.options) && this.props.options.length > 0) ? this.props.options.map(option => {
        return (
            <option key={option.id} value={option.id}>{option.name}</option>
        )
    }) : (<option>No Options Found</option>)}
</select>
Run Code Online (Sandbox Code Playgroud)

我该怎么做,才能选择第一个选项?我究竟做错了什么?

Ser*_*iuk 8

默认情况下会选择您的第一个选项。如果需要 - 您可以创建一个空选项,然后您可以选择第一个选项。

render() {
    const options = this.props.options.map(option =>
      <option key={option.id} value={option.id}>{option.name}</option>
    )

    return (
      <select
        className="form-control"
        name={this.props.name}
        onChange={this.handleChange.bind(this)}
      >
        <option value="">Select option</option>
        {options}
      </select>
    )
  }
Run Code Online (Sandbox Code Playgroud)

  • 还有其他没有空选项的方法吗? (2认同)