gpt4 book ai didi

javascript - React - 改变子组件的状态

转载 作者:行者123 更新时间:2023-11-30 15:00:37 27 4
gpt4 key购买 nike

我试图在另一个组件中更改我的状态。我已经通过props

状态
  constructor(props) {
super(props);

this.handleClick = this.handleClick.bind(this);

this.state = {
isOpen: false
};
}

<MobileContent isOpen={this.state.isOpen} />

在我的 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;

感谢帮助!!

最佳答案

如果你想让子组件通知父组件,那么你应该传递一个额外的 prop 给子组件,它是一个函数。然后 child 可以这样调用它。所以在 parent 中:

constructor(props) {
super(props);

this.handleClick = this.handleClick.bind(this);

this.state = {
isOpen: false
};
}

<MobileContent isOpen={this.state.isOpen} onClose={this.handleClick}/>

在 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;
}

关于javascript - React - 改变子组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46591351/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com