gpt4 book ai didi

javascript - 将状态从子类传递给父类

转载 作者:行者123 更新时间:2023-11-29 15:55:24 26 4
gpt4 key购买 nike

我知道这可能是关于 React 的最常见问题,但没有一个答案对我有帮助。

我有 2 个类:

child

class Preview extends Component {
constructor(...args) {
super(...args);
this.state = {
isCommentOpen: false
};
this.handleComment = ::this.handleComment;

render() {
return(
button type="button" onClick={this.handleComment}>Comment</button>
)}
handleComment(){
this.setState({isCommentOpen: !this.state.isCommentOpen});
}
export default Preview;

parent

class Profile extends Component {
render(){
return(
<div>
<_.Preview />
//the place where I want to add validation from the component above
{this.state.isCommentOpen ? <span>Cool</span> : null}
</div>
}

最佳答案

您不应该改变或直接分配 this.props,如其他答案所示:

this.props.isCommentOpen = !this.props.isCommentOpen // <-- DON'T DO THIS! 🎃

相反,你应该有一个回调函数让父组件更新子组件:

class Profile extends Component {

constructor(props) {
super(props);
this.state = {
isCommentOpen: false;
}
this.handleComment = this.handleComment.bind(this); // <-- important!
}

handleComment() {
this.setState({ isCommentOpen: !this.state.isCommentOpen });
}

render() {
return (
<div>
<Preview handleComment={this.handleComment} />
{ this.state.isCommentOpen ? <span>Cool</span> : null }
</div>
)
}
}

export default Profile

然后子组件只需要调用this.props.handleComment:

// Child Component:
class Preview extends Component {

render() {
return(
<button type="button" onClick={this.props.handleComment}>Comment</button>
}
}

export default Preview;

关于javascript - 将状态从子类传递给父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58368544/

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