【问题标题】:How can I create a drop down list from a state array?如何从状态数组创建下拉列表?
【发布时间】:2019-08-09 02:04:22
【问题描述】:

我目前正在尝试在 react 中呈现一个下拉列表,该列表将显示时间列表。用户应该能够选择一个特定的值,并且该值将通过 onChange() 在状态内更新。我的问题是我正在尝试使用选择,但是当我单击它时,我的下拉列表没有显示任何内容。任何帮助将不胜感激,谢谢。

这是我目前拥有的

我的文件.js


export default class MyClass extends Component {
    constructor(props){
    super(props);

    this.state = {

    times: ["1:00", "2:00", "3:00"]

    }
}

RenderList(){
 let tempArray = [];
   let times = this.state.times;

        for(var i = 0; i < times.length; i++){
           tempArray.push(<option>{times[i]}</option>)
        }

        return tempArray
}

return (
<div
  <select>{this.RenderList()}</select>
</div>
);

}

我有点希望在下拉列表中看到一个时间列表,但该列表为空。

【问题讨论】:

  • i &lt; myArray,你将一个数字与一个数组进行比较,它应该是i &lt; myArray.length
  • @EmileBergeron 刚刚更新它并给我一个错误:无法读取未定义的属性“长度”
  • 如果是这样,没有minimal reproducible example,我们无能为力。
  • @EmileBergeron 刚刚更新了您现在应该能够复制它的确切文件
  • 您只是缺少render 函数才能正确呈现。但German's answer 是这里最好的方法,onChange 处理程序也是如此。

标签: javascript html node.js reactjs


【解决方案1】:

这就是你要找的吗?您需要地图来呈现选项,我希望这会有所帮助!

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      times: ["1:00", "2:00", "3:00"]
    }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e) {
    console.log(e.target.value)
  }

  render() {
    const {times} = this.state;
    return (
      <select onChange={this.handleChange}>
         {times.map(time => {
           return (
             <option value={time}> {time} </option>
           )
         })}
    </select>
    )
  }
}
render(<App />, document.getElementById('root'));

【讨论】:

  • 如果时间是我状态的一部分,我尝试通过执行 this.state.times.map 来访问它,我收到错误:无法读取未定义的属性“地图”
  • 哦,这是因为我在使用 react hooks!,你熟悉 hooks 吗?如果您愿意,我可以将其更改为类组件。或者我可以解释一下什么是钩子;)
  • 抱歉不熟悉 react hooks。是的,如果你能把它改成一个很棒的类组件。
  • 我改了!如果您有任何问题,请告诉我!我希望这是有道理的
  • 仍然给我同样的错误:无法读取未定义的属性“地图”
【解决方案2】:

我想我会这样做。

import React, {Component} from 'react'

class ComponentName extends Component{
    state = {
        myArray: ["1:00", "2:00", "3:00"]}
    }


     render() {
         return (
             <select>
                 {this.state.myArray.map(optn => (
                     <option>{optn}</option>
                 ))}
             </select>
         )
     }

     export default ComponentName

希望对你有帮助

【讨论】:

  • 你的意思是 吗?
  • 如果你只是从箭头函数返回,你可以省略{},但是当你返回一个jsx元素或对象时,你可能需要将它包装在()中。
  • 但我实际上意识到你没有在RenderList 函数中更新你的状态,所以你可以映射到你的myArray 并删除你的RenderList 函数。 (我现在正在更新我的答案)
  • 下拉列表中不显示任何内容
  • 您的代码中仍然存在语法错误,我很难理解您的答案中缺少什么。
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 2016-05-03
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2018-02-23
相关资源
最近更新 更多