如何在同一级别的组件之间传递东西?
How do I pass things between components on the same level?
我有一个以下形式的 React 应用程序:
<App>
<ParentComponent>
<FormComponent>
<AnotherComponent>
</ParentComponent>
</App>
我希望能够通过单击 <AnotherComponent>
中的元素来更新 <FormComponent>
的一些状态值。
我不想将它们放在一起,而是让它们并排放置。我不想提升 <FormComponent>
状态,因为它封装得很好。
实现此目标的最佳方法是什么?我可以只做反应还是我需要 RxJS/something 其他?
React中的数据Flows Down.
如果您不想 lift the state up, what's left is Context API 或任何状态管理库,如 Redux 和 MobX(两者都使用不同的策略实现 Context API)。
但是,状态仍然是"above" FormComponent
(你还在提升状态)。
const Context = React.createContext();
const ParentComponent = () => {
const contextState = useState(DEFAULT_STATE);
return (
<Context.Provider value={contextState}>
<FormComponent />
<AnotherComponent />
</Context.Provider>
);
};
const FormComponent = () => {
const [, setState] = useContext(Context);
// use setState
};
const AnotherComponent = () => {
const [state] = useContext(Context);
// valid state updated from FormComponent
};
据我所知,"right thing" 在这些情况下要做的是将状态向上移动一级,进入您的父组件。
If you have a look at the Intro to React:
To collect data from multiple children, or to have two child components communicate with each other, you need to declare the shared state in their parent component instead.
"Lifting state up" 在 React 应用程序中很常见,不需要引入像 Redux 或 RxJS 这样的状态管理解决方案。
我有一个以下形式的 React 应用程序:
<App>
<ParentComponent>
<FormComponent>
<AnotherComponent>
</ParentComponent>
</App>
我希望能够通过单击 <AnotherComponent>
中的元素来更新 <FormComponent>
的一些状态值。
我不想将它们放在一起,而是让它们并排放置。我不想提升 <FormComponent>
状态,因为它封装得很好。
实现此目标的最佳方法是什么?我可以只做反应还是我需要 RxJS/something 其他?
React中的数据Flows Down.
如果您不想 lift the state up, what's left is Context API 或任何状态管理库,如 Redux 和 MobX(两者都使用不同的策略实现 Context API)。
但是,状态仍然是"above" FormComponent
(你还在提升状态)。
const Context = React.createContext();
const ParentComponent = () => {
const contextState = useState(DEFAULT_STATE);
return (
<Context.Provider value={contextState}>
<FormComponent />
<AnotherComponent />
</Context.Provider>
);
};
const FormComponent = () => {
const [, setState] = useContext(Context);
// use setState
};
const AnotherComponent = () => {
const [state] = useContext(Context);
// valid state updated from FormComponent
};
据我所知,"right thing" 在这些情况下要做的是将状态向上移动一级,进入您的父组件。
If you have a look at the Intro to React:
To collect data from multiple children, or to have two child components communicate with each other, you need to declare the shared state in their parent component instead.
"Lifting state up" 在 React 应用程序中很常见,不需要引入像 Redux 或 RxJS 这样的状态管理解决方案。