在reactjs

时间:2018-11-15 16:58:15

标签: javascript reactjs

我正在尝试获取动态下拉列表中的“键”值,如下所示:

searchSubmit(e){    
  const s = e.target.value;
  alert(s);
}

我的下拉列表如下:

<select
  className="textboxstyle"
  onChange={this.searchSubmit}
>
  <option key='-1'>Select Brand</option>
  <option key='0'>ALL</option>
  {optionItems}
</select>

我的动态下拉列表填充如下,

let brands = this.state.brands;
let optionItems = brands.map((brand) =>
  <option key={brand.id}>{brand.name}</option>
);

但是,当我选择选项时,警报将显示所选值的名称,而不是键。如何获得“关键”价值? 谢谢

1 个答案:

答案 0 :(得分:1)

React使用key道具来区分数组中的所有元素。如果您希望value成为id的{​​{1}},则可以将其用作brandvalue

示例

key
class App extends React.Component {
  state = {
    brands: [{ id: 1, name: "Foo" }, { id: 2, name: "Bar" }]
  };

  searchSubmit = e => {
    const { value } = e.target;
    alert(value);
  };

  render() {
    const { brands } = this.state;

    return (
      <select onChange={this.searchSubmit}>
        <option value="-1">Select Brand</option>
        <option value="0">ALL</option>
        {brands.map(brand => (
          <option value={brand.id} key={brand.id}>
            {brand.name}
          </option>
        ))}
      </select>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));