React Native中的useContext

埃里克·蒙哈斯(Erik Monjas)

我一直在尝试在React Native中使用上下文挂钩,但是它似乎不起作用,它返回undefined。但是,当我使用<Context.Consumer>时,它工作正常,您知道React Native是否支持useContext吗?

安东尼奥·佩莱格里尼

在react native中绝对支持useContext。使用React.createContext()创建上下文。

export const AppStateContext = React.createContext();

const AppStateProvider = props => {

  const contextValue={...yourContext}

  return (
    <AppStateContext.Provider value={contextValue}>
      {props.children}
    </AppStateContext.Provider>
  );
};

这样包装您的应用。

<AppStateProvider>
    <App />
</AppStateProvider>

然后,您可以使用useContext钩子访问嵌套组件中的上下文。

import {AppStateContext} from './AppStateProvider';

function YourComponent(props) {
  const {context} = useContext(AppStateContext)
  
  ...
    return (
      <View>
      ...
      </View>
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章