首页 > 解决方案 > reactjs, putting n options together in a select

问题描述

I have the following piece of jsx in my reactjs program,

<select onChange = {this.selectChange}>
  <option>{this.state.array[0]}</option>
  <option>{this.state.array[1]}</option>
  <option>{this.state.array[2]}</option>
  <option>{this.state.array[3]}</option>
</select>

Its actually much longer than this, I have 32 elements in the array so I'd like to find a more compact way of doing this. For example, I was thinking something like this:

<select onChange = {this.selectChange}>
  {for (var n=0; n<32; n++) <option>{this.state.array[n]}</option>}
</select>

However that doesn't work. How might I do this? Thanks

标签: reactjs

解决方案


const options = this.state.array.map(op => {
    return <option>{op}</option>
  });

  return (
    <select onChange = {this.selectChange}>
      {options}
    </select>
  );

为了提高可读性,您可以将它们分成另一个变量options,然后在该变量中使用映射函数生成单个项目。

要回答您的问题,您的方法行不通是因为缺少return密钥


推荐阅读