简体   繁体   English

在 REACT 兄弟组件之间传递数据

[英]Passing Data between REACT sibling component

A (Parent)
    |---- B (Child)
    |---- C (Child)

I'm trying to pass the data to sibling components[like from B to C ],我正在尝试将数据传递给兄弟组件[例如从 B 到 C],

First, in the parent component [A], I have defined the callback function and passing this callback function to child [B],首先,在父组件[A]中,我定义了回调函数并将这个回调函数传递给子组件[B],

handleCallback = (data) => {
    console.log('In parent', datafromChild)
    this.setState.listDataFromChild = data
  }

<LaunchPageButtons ParentCallBack={this.handleCallback} />

In the child component [B], I'm calling the callback as,在子组件 [B] 中,我将回调称为,

this.props.ParentCallBack('true')

Here I'm able to get the value in the callback function of parent [A] and updating the parent state.在这里,我可以获取父 [A] 的回调函数中的值并更新父状态。 Till now its fine and working直到现在它的罚款和工作

Now I want to send the same data to Child [C] so I'm passing it as props from parent component[A] as,现在我想将相同的数据发送给 Child [C] 所以我将它作为来自父组件 [A] 的 props 传递,

<ChannelsModularGrid buttonselect={this.state.listDataFromChild} />

In the Child[C], to test whether I'm getting the data, I have put a check in one of the function as,在 Child[C] 中,为了测试我是否正在获取数据,我在其中一个函数中进行了检查,

if (this.props.buttonselect) {
      debugger //eslint-disable-line
      console.log('test')
    }

I'm not getting the controll/debugger in the child component[C] at all.我根本没有在子组件 [C] 中获得控制/调试器。 Please help me out to understand how to pass data from A to C in my case请帮助我了解在我的情况下如何将数据从 A 传递到 C

Remember that setState is a function.请记住setState是一个函数。 In your parent's callback, instead of assigning to a property of setState , call the function with the updated slice of the state:在您父母的回调中,不是分配给setState的属性,而是使用更新的状态切片调用函数:

handleCallback = (data) => {
  console.log('In parent', datafromChild)
  this.setState({
    listDataFromChild: data
  })
}

as @cubbrr answers the question already, I will only add that although you did not specify the context of your code, errors might also happen if you do not properly bind functions, as this might set the state of the child component instead of the parent.由于@cubbrr 已经回答了这个问题,我只会补充一点,尽管您没有指定代码的上下文,但如果您没有正确绑定函数,也可能会发生错误,因为这可能会设置子组件而不是父组件的状态. So, for your case, either bind in the constructor or by sending the function as an arrow function which automatically binds:因此,对于您的情况,要么在构造函数中绑定,要么将函数作为自动绑定的箭头函数发送:

1) 1)

constructor(props){ super(props); this.handleCallback = this.handleCallback.bind(this) }

...


<LaunchPageButtons ParentCallBack={this.handleCallback} />

OR或者

2) 2)

<LaunchPageButtons ParentCallBack={(data) => { console.log('In parent', datafromChild); this.setState({listDataFromChild: data}); }} />

You can read more about binding here: https://reactjs.org/docs/handling-events.html您可以在此处阅读有关绑定的更多信息: https : //reactjs.org/docs/handling-events.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM