[英]Pass state from child component to parent component
我有2个jsx文件,
我怎样才能从Child.jsx得到this.props.result在Parent.jsx?
文件Child.jsx:
class Child extends React.Component{
constructor(props) {
super(props);
this.state = {
result: 'logout'
};
this.login_action = this.login_action.bind(this);
this.logout_action = this.logout_action.bind(this);
}
login_action(){
this.setState({result: 'login'})
}
logout_action(){
this.setState({result: 'logout'})
}
render(){
return(
<div>
<h1>{this.state.status}</h1>
<button onClick={this.login}>Login</button>
<button onClick={this.logout}>Logout</button>
</div>
)
}
}
出口默认儿童;
文件Parent.jsx:
class Parent extends React.Component {
render () {
if(this.props.result.localeCompare("login") > -1){
return(<Child status="logout" />)
}else{
return(<Child status="logout"/>)
}
}
}
render(<Parent/>, document.getElementById('app'));
正如文件所说,
在React中,共享状态是通过将其移动到需要它的组件的最近共同祖先来完成的。 这称为“提升状态”。 ( https://facebook.github.io/react/docs/lifting-state-up.html )
您应该将“结果”状态移动到父组件。 有关从代码中提升状态的示例,请参阅此Plunker 。
您需要将回调函数从Parent传递给Child。 像这样:
Parent.jsx
class Parent extends React.Component {
render () {
if(this.props.result.localeCompare("login") > -1){
return(<Child onResultChange={(res) => this.onResultChange(res)} status="logout" />)
}else{
return(<Child onResultChange={(res) => this.onResultChange(res)} status="logout"/>)
}
}
onResultChange(newResult) {
//do what you need with new result value here
}
}
render(<Parent/>, document.getElementById('app'));
Child.jsx
constructor(props) {
super(props);
this.state = {
result: 'logout'
};
this.login_action = this.login_action.bind(this);
this.logout_action = this.logout_action.bind(this);
}
login_action(){
this.setState({result: 'login'});
this.props.onResultChange('login');
}
logout_action(){
this.setState({result: 'logout'});
this.props.onResultChange('logout');
}
render(){
return(
<div>
<h1>{this.state.status}</h1>
<button onClick={this.login}>Login</button>
<button onClick={this.logout}>Logout</button>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.