gpt4 book ai didi

javascript - 以对象作为属性值来 react 选择选项

转载 作者:技术小花猫 更新时间:2023-10-29 12:46:17 24 4
gpt4 key购买 nike

当我想更改所选选项时,我遇到了 react 问题。问题是该值是一个对象,我无法在选项值属性中传递它。

请看下面的代码:

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 无法在最终 View 的属性中嵌入 javascript 对象。我说的对吗?

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

最佳答案

您可以使用 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>
}
}

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

我取决于你的要求。如果你想至少显示一个选项,你可以保留它而不是 null

关于javascript - 以对象作为属性值来 react 选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com