我有一个使用<select>
元素呈现<option>
的组件。当发生任何更改时,我想更改组件的状态以保留当前所选选项的值。据我所知,我没有别的选择来保持这个值,因为React JS中的props必须是不可变的。
当我通知 parent 更改时,问题就来了。我使用从handleChange
回调到父级的handleChange
函数的方法来执行此操作。因此,在child元素中,我实际上调用了handleChange
函数,设置了新状态并调用了回调(父级的handleChange
)。但是随后在父函数中,当我要求state属性的值时,我收到了旧的(似乎仍未设置新的)。
有什么想法吗?
最佳答案
我建议使用单个数据流模式(例如Flux或Reflux)来构造您的应用程序,并避免这种错误和复杂的反向数据流。
根据我对您的问题的了解,如果没有Flux,您可以执行以下操作。
var React = require("react");
var ParentComponent = React.createClass({
handleChange: function(newOption){
console.log("option in child component changed to " + newOption);
},
render: function(){
return (
<div>
<ChildComponent handleChange={this.handleChange}/>
</div>
)
}
});
var ChildComponent = React.createClass({
getInitialState: function(){
return {
selectedOption: 0
};
},
handleChange: function(){
var option = this.refs.select.getDOMNode().value;
this.setState({ selectedOption: option});
// I'm passing the actual value as an argument,
// not this.state.selectedOption
// If you want to do that, do it in componentDidUpdate
// then the state will have been set
this.props.handleChange(option);
},
render: function(){
return (
<div>
<h4>My Select</h4>
{this.state.selectedOption}
<select ref="select"
onChange={this.handleChange}>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
)
}
});
编辑
添加了几个被遗忘的分号。这些天,我对Python的编码过多。
编辑2
更改了代码。您的问题可能是,如果您使用状态(
this.state.selectedOption
)中的值调用父级的handleChange,则该状态尚未设置,因此您必须提供实际值作为参数。如果您确实要使用this.state.selectedOption
,请在componentDidUpdate中调用父级的handleChange
。关于javascript - React.js onChange使 parent 知道改变的状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29477434/