首页 > 解决方案 > 循环遍历map函数

问题描述

我正在使用 map 函数循环遍历数组以返回 HTML 选择标签的选项标签。但这似乎不起作用。Project_titles 数组已正确填充数据。

我在其他地方使用了相同的代码,它在那里工作。

render() {
  <select
    id="sel4"
    onChange={event => this.setState({ project: event.target.value })}
  >
    {this.func()}
  </select>;
}

func() {
  this.state.project_titles.map(function(title, i) {
    return (
      <option key={i} value={title}>
        {title}
      </option>
    );
  });
}

选择标签应该填充选项,但它是空的。

标签: javascriptreactjs

解决方案


这行得通。您的代码的问题是您没有从 func() 函数返回最终的 Options 数组。

render(){
  <select
    id="sel4"
    onChange={event => this.setState({ project: event.target.value })}
  >
    {this.func()}
  </select>;
};

func = () => {
  return this.state.project_titles.map(function(title, i) {
    return (
      <option key={i} value={title}>
        {title}
      </option>
    );
  });
};

推荐阅读