Fri*_*lox 12 html javascript reactjs
当我想要更改所选选项时,我有一个问题.问题是该值是一个对象,我无法在选项值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>
}
}
Run Code Online (Sandbox Code Playgroud)
与
<Selector option={[{name: "name", obj:{...}}, ...]}>
Run Code Online (Sandbox Code Playgroud)
我需要使用所选选项的值更改组件的状态.当州改变时,我得到了什么"object Object".我想这是因为反应无法在最终视图的属性中嵌入javascript对象.我是对的?
而且,我obj在构造函数中将状态设置为null是否有正确的方法来执行此操作?
Jyo*_*aja 20
您可以利用index的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>
}
}
Run Code Online (Sandbox Code Playgroud)
而且,我在构造函数中将obj in state设置为null有没有正确的方法呢?
我取决于你的要求.如果您想要显示至少一个选项,您可以保留它而不是null
将对象JSON字符串作为值传递,然后解析它.
handleChange(event) {
let obj = JSON.parse(event.target.value); //object
}
render() {
<select onChange={handleChange}>
{this.props.listOption.map((option, index) =>
<option key={index}
value={JSON.stringify(option)}> //pass object string as value
{option.name}
</option>
)}
</select>
}
Run Code Online (Sandbox Code Playgroud)