gpt4 book ai didi

reactjs - React Native 中的 useContext

转载 作者:行者123 更新时间:2023-12-04 11:52:06 26 4
gpt4 key购买 nike

我一直在尝试在 React Native 中使用上下文 Hook ,但它似乎不起作用,它返回 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 钩子(Hook)访问嵌套组件中的上下文。

import {AppStateContext} from './AppStateProvider';

function YourComponent(props) {
const {context} = useContext(AppStateContext)

...
return (
<View>
...
</View>
);
}

关于reactjs - React Native 中的 useContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com