我正在尝试根据另一个组件的状态执行一些操作。我有一个选择框,当用户更改选项时我会更改状态。
<div className="post_privacy_div float_left">
<select className="review_privacy_select" onChange={this.commentOption}>
<option value="Comments with filter">Comments with filter</option>
<option value="Enable comments">Enable all comments</option>
<option value="Disable comments">Disable all comments</option>
</select>
</div>
函数
commentOption(e) {
this.setState({selectValue: e.target.value});
}
因此状态更改已成功完成。现在我想将此状态传递给另一个组件。我该怎么做?
基本上我正在尝试这样做,但在另一个组件中
if (this.state.selectValue === 'Enable comments') {
this.setState({
pendingcomment: !this.state.pendingcomment,
})
} else if (this.state.selectValue === 'Disable comments') {
this.setState({
pendingcomment: false,
allcomment: false,
})
} else {
this.setState({
pendingcomment: true,
allcomment: true,
})
}
最佳答案
在这种情况下,维护 parent
组件中的值,并将该值和函数从父组件传递到 Child1
(需要传递函数来更改父组件中的值),将值传递给 Child2
。
检查这个工作片段:
class Parent extends React.Component {
constructor(){
super();
this.state = { value: null}
this.change = this.change.bind(this)
}
change(value){
this.setState({value})
}
render(){
return(
<div>
<Child1 value={this.state.value} change={this.change}/>
<Child2 value={this.state.value}/>
</div>
)
}
}
class Child1 extends React.Component {
render(){
return(
<div>
In Child1:
<select value={this.props.value} onChange={(e) => this.props.change(e.target.value)}>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</div>
)
}
}
class Child2 extends React.Component {
render(){
return(
<div>In Child2: {this.props.value} </div>
)
}
}
ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
关于javascript - 在组件之间传递状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154760/