如何在子组件可以访问的上下文中创建方法?

IT技术 reactjs react-native react-context
2021-05-06 23:07:38

我有一个组件可以呈现:

<View>
   <SomeContext.Provider value={state}>
        {props.children}
   </SomeContext.Provider>
</View>

我不明白如何创建可通过以下方式访问的方法:

<View>
   <SomeContext.Provider>
        {(method) =>  
                <Button
                   title={"Magic"}
                   onPress={() => {
                     method()
                   }}
                 ></Button>
        }
   </SomeContext.Provider>
</View>
2个回答

消费者组件

您需要通过Context.Consumer相关 的直接后代来使用上下文Provider。这些文档有不错的示例,尽管它们混合了基于类的组件和功能组件。从嵌套组件更新上下文

沙盒:https : //codesandbox.io/s/react-context-consumer-passing-method-to-nested-child-forked-u0bi8

const initData = {
  data: { a: "Text from Context", b: "2" },
  method: () => {
    console.log("Method called.");
  }
};

const SomeContext = React.createContext();

export default function App() {
  return (
    <SomeContext.Provider value={initData}>
      <Content />
    </SomeContext.Provider>
  );
}

function Content() {
  return (
    <div>
      <SomeButton />
    </div>
  );
}

function SomeButton() {
  return (
    <SomeContext.Consumer>
      {({ data, method }) => <button onClick={method}>{data.a}</button>}
    </SomeContext.Consumer>
  );
}


使用上下文挂钩

所述useContext钩也是可用的,并且可能提供更熟悉的模式。上下文的消费者仍然需要是提供者的后代,但它是通过钩子而不是消费者组件来访问的。

沙盒:https : //codesandbox.io/s/react-context-passing-method-to-nested-child-1fcno

const initData = {
  data: { a: "Text from Context", b: "2" },
  method: () => {
    console.log("Method called.");
  }
};

const SomeContext = React.createContext();

export default function App() {
  return (
    <SomeContext.Provider value={initData}>
      <Toolbar />
    </SomeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <SomeButton />
    </div>
  );
}

function SomeButton() {
  const { data, method } = React.useContext(SomeContext);
  return <button onClick={method}>{data.a}</button>;
}

上下文counsumer文档实际上告诉了你一切你需要知道:

订阅上下文更改的 React 组件。这使您可以订阅功能组件中的上下文。

需要一个函数作为一个孩子。该函数接收当前上下文值并返回一个 React 节点。传递给函数的 value 参数将等于树中最接近此上下文的 Provider 的 value prop。如果上面的上下文没有提供者,则 value 参数将等于传递给 createContext() 的 defaultValue。

因此,在您的示例中,您需要将您想要的方法传递给提供者:

const method = () => {};

<View>
  <SomeContext.Provider value={{ method }}>
    {props.children}
  </SomeContext.Provider>
</View>

然后在消费者中你可以这样称呼它:

<View>
  <SomeContext.Consumer>
    // using destructuring here,
    // so its ({ method }) instead of (method)
    {({ method }) =>  
      <Button
        title={"Magic"}
        onPress={() => method()} />
    }
  </SomeContext.Consumer>
</View>

此外,消费者组件位于提供者内部也很重要。