【发布时间】:2021-09-13 06:14:32
【问题描述】:
目前我在我的 react 应用程序中使用 reactjs context api,我想将数据从子组件传递到父组件,但我不确定如何实现。这是我的完整应用布局:
- Component 1 (App.js) [contextOneProvider]
- Component 2
- Component 3 ==> Need a state from child component 7
- Component 4
- Component 5 [contextOneConsumer, getting state from component 1]
- Component 6
- Component 7 ==> Need to send a state to parent component 3
- Component 8 [contextOneConsumer, getting state from component 1]
正如你在上面看到的,我已经创建了一个 context(contextOne),contextOne 的提供者用于组件 1,contextOne 的消费者用于组件 5 和组件 8。现在父组件 3 需要一个数据/来自子组件 7 的状态,这就是问题所在,如何将子组件 7 中的一条数据/状态传递回父组件 3?
如果我在没有反应上下文 api 的情况下执行此操作,我需要将一个函数/方法从父组件 3 向下传递到子组件 7,然后在子组件 7 中调用它并备份数据/状态,我不会这样做想这样做,因为它是一个深支柱钻和组件4,组件5,组件6不需要那个功能/方法,它只存在于组件4,组件5和组件6是因为我需要它通过直到子组件 7 才能使用它。
我能想到的另一种方法是创建另一个新上下文(contextTwo)并在组件 3 上使用新上下文的提供者,在组件 7 上使用新上下文的提供者,但创建一个全新的上下文只是为了将一条数据/状态传回直到父组件 3,我也不认为这是一个好主意。
代码:
父组件 3
const componentThree = () => {
return (
<div>
<span> // Receive someRandomId value from child component 7 and use in here </span>
<ComponentFour/>
</div>
);
}
子组件 7
const componentSeven = () => {
const handleOnClick = () => {
// Pass someRandomId value back up to parent component 3
const someRandomId = 4;
};
return (
<div>
<ComponentEight/>
<button onClick={handleOnClick} ></button>
</div>
);
}
那么,如何在不进行道具钻探或创建全新上下文的情况下将一条数据/状态从子组件 7 传回父组件 3,只是为了将该一条数据/状态传回父组件?
抱歉,这是我第一次使用 react context api。
【问题讨论】:
标签: javascript reactjs react-context