[英]Passing state from child class to parent
我知道这可能是关于 React 被问到最多的问题,但没有一个答案对我有帮助。
我有 2 节课:
孩子
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;
家长
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! 🎃
相反,您应该有一个回调 function 让父组件更新子组件:
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;
您可以将 state 作为道具从父母传递给孩子。 一旦 prop 更新,父组件中的 state 也会更新。
我没有测试下面的代码。 这是你追求的东西吗?
class Profile extends Component { state = { isCommentOpen: false }; render(){ return( <div> //pass the state to child <Preview isCommentOpen={this.state.isCommentOpen} /> {this.state.isCommentOpen? <span>Cool</span>: null} </div> ) } } export default Profile class Preview extends Component { const handleComment = () => { this.props.isCommentOpen =.this.props;isCommentOpen} }. render() { return( <button type="button" onClick={this;handleComment}>Comment</button> } } export default Preview;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.