小编典典

使用对象作为属性值来反应选择选项

reactjs

当我想更改所选选项时,我的反应有问题。问题在于该值是一个对象,我无法在选项值属性中传递它。

请参见以下代码:

class Selector extends React.Component {
  contructor(props) {
    super(props)
    this.state = { obj: null }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e) {
    this.setState({obj: e.target.value})
  }

  render() {
    <select onChange={handleChange}>
     {this.props.listOption.map((option, index) => 
       <option key={index} value={option.obj}>
         {option.name}
       </option>
     )}
    </select>
  }
}

<Selector option={[{name: "name", obj:{...}}, ...]}>

我需要使用所选选项的值更改组件的状态。状态改变时我得到什么"object Object"。我想发生这种情况是因为react无法将javascript对象嵌入最终视图的属性中。我是正确的?

而且,我obj在构造函数中将state 设置为null是否有正确的方法?


阅读 254

收藏
2020-07-22

共1个答案

小编典典

您可以利用indexoptions

class Selector extends React.Component {
  contructor(props) {
    super(props);
    this.state = { obj: null }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e) {
    this.setState({obj: this.props.listOption[e.target.value].obj})
  }

  render() {
    <select onChange={handleChange}>
     {this.props.listOption.map((option, index) =>
       <option key={index} value={index}>
        {option.name}
       </option>
      )}
    </select>
  }
}

此外,我在构造函数中将obj的状态设置为null是否有正确的方法?

我要看你的要求 如果您希望至少显示一个选项,则可以保留该选项而不是null

2020-07-22