Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - React selecting option with object as attribute value

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.

See the following code:

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>
  }
}

and with

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

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make use of index of options

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>
  }
}

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...