简体   繁体   English

React子组件调用兄弟组件上的函数

[英]React child component to invoke a function on a sibling componenet

It's going to be hard to verbalise this question. 要解释这个问题很难。 In React, is there a way for a deeply (2 levels deep from the parent) nested child component to invoke a function that it has a sibling relationship with ? 在React中,是否有一种方法可以深入(父级的2级深度)嵌套子组件调用一个与它有兄弟关系的函数? (the sibling being 1 level deep from the parent, but lacking a top-down relationship with the deeply nested child) (兄弟姐妹离父母一层深,但与深层嵌套的孩子缺乏自上而下的关系)

The function is meant to change the state of the sibling component, so it needs to be invoked as a method on the sibling component's class 该函数用于更改兄弟组件的状态,因此需要在兄弟组件的类上调用它作为方法

See I know that I can pass a function as a prop to a child and have it get invoked on the parent's class, but can this happen with a sibling somehow? 看,我知道我可以将一个函数作为一个prop传递给一个孩子并让它在父类的上面调用,但是这可能会以某种方式与兄弟一起发生吗?

Please let me know if this makes sense, if not I can throw together a simple example of what I mean, There is too much code for me to paste. 请告诉我这是否有意义,如果不是,我可以把一个简单的例子放在一起我的意思,我有太多的代码要粘贴。

As you say, you can invoke a function in a parent from a child by passing the function as a prop. 正如您所说,您可以通过将函数作为prop传递来调用子节点中的父节点中的函数。 In the parent you can then change some state which causes a re-render of the parent, passing the new state/props down to the sibling you want to update. 在父级中,您可以更改某个状态,从而导致重新呈现父级,将新状态/ props向下传递给要更新的兄弟。

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

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