目前我在我的 react 应用程序中使用 reactjs 上下文 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?
如果我在没有 react context 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。
答案 0 :(得分:0)
请按照以下步骤避免创建新上下文:
在提供者组件中添加一个新状态:
const [randonmId, setRandomId] = useState();
将 randomId
和 setRandomId
添加到传递给提供程序的值
value={{...previous things, randomId, setRandomId }}
使用组件 3 中的上下文,但仅用于获取 randomId
另外,使用组件 7 中的上下文并在处理程序中使用 setRandomId
const handleOnClick = () => {
const someRandomId = 4;
setRandomId(someRandomId);
};
在组件 3 中:
{randomId && <span>{randomId}</span>}
因为在调用 comp 7 的处理程序之前 randomId
将是未定义的