获取不是孩子的组件来从另一个组件接收道具

时间:2018-06-19 22:59:23

标签: reactjs

我的组件-

ProfileHeader
-通知

发布
- 注释
--LikePost

我希望ProfileHeader组件中的Notifications组件能够在用户对帖子发表评论或喜欢帖子时接收道具。我希望通知组件能够接收道具,以便它可以更新并重新呈现新的通知。我想在下面执行的操作示例:

handleLikeCount(){
    let count = this.state.likeCount;

    let dummyData = {
        username: 'hatface',
        userid: '0201',
        date_posted: '(data)',
        display_picture: '(image)'
    }

    if(this.state.liked){
        this.setState({
            likeCount: count - 1,
            liked: false
        }, () => {
            <Notifications notificationFrom={dummyUser} />
        }); 
    }
    else{
        ....
    }


}

谢谢

1 个答案:

答案 0 :(得分:0)

Two ways to do it:

  • define a component that will be the parent of both ProfileHeader and of Post. The posts will be in this new component's state. This new component will pass callbacks to its children components. These callbacks will be called by the children components when they want to change posts.
  • use redux, define global state that will be accessible from multiple components