1

我有以下上下文

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”,我需要一种方法将在屏幕(消费者)内操作我的有状态数据的方法传递给提供程序。

4

2 回答 2

1

你不能,在 React 中数据只会向下流动

这通常称为“自上而下”或“单向”数据流。任何状态始终由某个特定组件拥有,并且从该状态派生的任何数据或 UI 只能影响树中它们“下方”的组件。

您的回调(“onReportButtonPress”、“onDeleteButtonPress”)必须在提供者的范围内可用。

<ExampleContext.Provider
  value={{
    onReportButtonPress,
    onDeleteButtonPress,
  }}
>
  {children}
</ExampleContext.Provider>;
于 2021-07-21T19:48:12.787 回答
0

在 Consumer 组件中渲染 SomeCustomComponent。这是 React 做事的方式 :)

于 2021-07-21T20:47:34.103 回答