[英]React - Change state in child component
I trying to change my state in another component. 我试图在另一个组件中更改状态。 I have passed the state by props
我已经通过道具通过了状态
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isOpen: false
};
}
<MobileContent isOpen={this.state.isOpen} />
In my MobileContent component i want to change the state when i click on the element. 我想在我的MobileContent组件中单击该元素时更改状态。
class MobileContent extends Component {
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close" onClick={this.handleClick} >X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}
}
export default MobileContent;
Thanks for the help !! 谢谢您的帮助 !!
If you want the Child component to notify the parent, then you should pass an additional prop down to the child which is a function. 如果要让Child组件通知父级,则应将附加的prop传递给child,这是一个函数。 The child can then call that.
然后,孩子可以打电话给他。 So in the parent:
因此在父项中:
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isOpen: false
};
}
<MobileContent isOpen={this.state.isOpen} onClose={this.handleClick}/>
And in the child: 而在孩子中:
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close" onClick={this.props.onClose}>X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.