1 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
您不應(yīng)該改變或直接分配this.props,如另一個(gè)答案所示:
this.props.isCommentOpen = !this.props.isCommentOpen // <-- DON'T DO THIS! ??
相反,你應(yīng)該有一個(gè)回調(diào)函數(shù)讓父組件更新子組件:
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
然后子組件只需要調(diào)用this.props.handleComment:
// Child Component:
class Preview extends Component {
render() {
return(
<button type="button" onClick={this.props.handleComment}>Comment</button>
}
}
export default Preview;
添加回答
舉報(bào)