我有以下上下文
import React, { createContext, useRef } from "react";
const ExampleContext = createContext(null);
export default ExampleContext;
export function ExampleProvider({ children }) {
const myMethod = () => {
};
return (
<ExampleContext.Provider
value={{
myMethod,
}}
>
{children}
<SomeCustomComponent
/* callback={callbackPassedFromConsumer} */
/>
</ExampleContext.Provider>
);
}
如您所见,它呈现了一个自定义组件,该组件接收一个方法作为道具。此方法在特定屏幕中定义,该屏幕使用此上下文。
如何将其从屏幕传递给提供者?
这就是我使用上下文的方式(使用 HOC):
import React from "react";
import ExampleContext from "../../../contexts/ExampleContext";
const withExample = (Component) => (props) =>
(
<ExampleContext.Consumer>
{(example) => (
<Component {...props} example={example} />
)}
</ExampleContext.Consumer>
);
export default withExample;
这是我需要传递给上下文提供程序的方法的屏幕
function MyScreen({example}) {
const [data, setData] = useState([]);
const myMethodThatINeedToPass = () => {
...
setData([]);
...
}
return (<View>
...
</View>);
}
export default withExample(MyScreen);
更新:
我正在尝试这样做,因为在我的真实提供商中,我有一个 BottomSheet 组件,它呈现两个按钮“删除”和“报告”。这个组件是可重用的,所以,为了避免重复自己,我使用了上下文提供程序。
见:https ://github.com/gorhom/react-native-bottom-sheet/issues/259
然后,由于在提供程序中呈现的底部工作表组件可以接收可选道具“onReportButtonPress”或“onDeleteButtonPress”,我需要一种方法将在屏幕(消费者)内操作我的有状态数据的方法传递给提供程序。