【问题标题】:Looping through map function循环遍历map函数
【发布时间】:2019-12-10 12:08:56
【问题描述】:

我正在使用 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>
    );
  });
}

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

【问题讨论】:

  • 也许你应该从函数中return
  • func 返回 void... 只返回映射数组
  • render 不返回任何内容,func 也不返回任何内容。
  • 请您尝试将 return 指令放入您的 render() 和 func() 函数中吗? render() { return &lt;select ... &gt;...&lt;/select&gt; } func() { return ... ;}

标签: javascript reactjs


【解决方案1】:

这行得通。您的代码的问题是您没有从 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>
    );
  });
};

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2014-06-02
    • 2016-08-11
    • 2015-10-03
    相关资源
    最近更新 更多