将状态从子类传递给父类

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


我有两个班级:


孩子


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>

}


芜湖不芜
浏览 166回答 1
1回答

狐的传说

您不应该改变或直接分配this.props,如另一个答案所示:this.props.isCommentOpen = !this.props.isCommentOpen // <-- DON'T DO THIS! 🎃相反,你应该有一个回调函数让父组件更新子组件:class Profile extends Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; isCommentOpen: false;&nbsp; &nbsp; }&nbsp; &nbsp; this.handleComment = this.handleComment.bind(this); // <-- important!&nbsp; }&nbsp; handleComment() {&nbsp; &nbsp; this.setState({ isCommentOpen: !this.state.isCommentOpen });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <Preview handleComment={this.handleComment} />&nbsp; &nbsp; &nbsp; &nbsp; { this.state.isCommentOpen ? <span>Cool</span> : null }&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}export default Profile然后子组件只需要调用this.props.handleComment:// Child Component:class Preview extends Component {render() {&nbsp; return(&nbsp; &nbsp; <button type="button" onClick={this.props.handleComment}>Comment</button>&nbsp; }}export default Preview;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript