使用对象作为属性值来反应选择选项 [英] React selecting option with object as attribute value

查看:62
本文介绍了使用对象作为属性值来反应选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an issue with react when I want to change the selected option. The problem is that the value is an object and I can't pass it in option value attribut.

请参见以下代码:

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对象嵌入最终视图的属性中.我是对的吗?

I need to change the state of the component with the value of the selected option. What I get when the state change is "object Object". I suppose this happens because react can't embed javascript object in attribut of final view. I am right?

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

Moreover, I set obj in state as null in the constructor Is there a right way to do it?

推荐答案

您可以使用optionsindex

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. 正确的方法吗?

Moreover, I set obj in state as null in the constructor Is there a right way to do it?

我取决于您的要求.如果要显示至少一个选中的选项,可以保留该选项而不是null

I depends on your requirement. If you want to show at least one option as selected you can keep that instead of null

这篇关于使用对象作为属性值来反应选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆