繁体   English   中英

如何从 React 中的另一个兄弟组件触发兄弟组件 function?

[英]How to trigger sibling component function from another sibling component in React?

在 React 中,我有一个包含三个兄弟组件的父组件,例如:

<div>
   <Component1/>
   <Component2/>
   <Buttons/>
</div>

我想从<Buttons/>组件触发<Component1/><Component2/>中定义的函数。 目前我正在使用useImperativeHandleforwardRef<Component1/><Component2/>导出函数,并通过其props将它们传递给<Buttons/>组件。

它有效,但似乎不是最好的方法。 如果我不想将<Component1/><Component2/>函数以及 state 处理移动到父组件,那么推荐的 React 模式是什么?

我会建议将 state 移动到父级,但由于您不希望这样做,您可以使用带有钩子的上下文

创建上下文

export const AppContext = React.createContext();

在需要的地方使用它(先导入上下文和 useContext)

const {state, dispatch} = useContext(AppContext);

官方文档: https://reactjs.org/docs/hooks-reference.html#usecontext

暂无
暂无

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

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