如何更新父级的状态'的父组件在react中

How to update state of parent's parent component in react?

本文关键字:组件 react 状态 更新 何更新      更新时间:2024-02-22

我在玩fb关于评论框的教程。让我们想象一下,我已经添加了删除评论的功能,所以在评论组件-中会有这样的东西

onClick={this.handleCommentDelete}

如何在不将回调传播到整个commentList组件然后传播到注释组件的情况下触发commentBox父组件的状态更改?

<commentBox>
  <commentList>
    <comment>

我使用PubSub模式在组件之间进行通信。在评论框中:

componentDidMount: function() {
    PubSub.subscribe("COMMENT_DELETED", function( msg, data ){
        console.log( data ); //logs "commentId"
    });
}

在handleCommentDelete:中

PubSub.publish("COMMENT_DELETED", {commentId: commentId});

对于PubSub,我使用这个库(当然还有其他库):https://www.npmjs.com/package/pubsub-js.