1 回答
TA贡献1757条经验 获得超7个赞
这将是一个将上下文与类组件一起使用的工作示例。请记住,当您从一个类访问它时,您只能使用一个上下文。
在这里我创建了一个按钮组件来更新上下文。如您所见,我在上下文中有一个函数,它会更新我们从 useState 传递 setAppState 函数的上下文。
const AppContext = React.createContext({
appState: { IsLoading: true, IsLoggedIn: false },
setAppState: () => {},
});
export default function App() {
const [appState, setAppState] = React.useState({
IsLoading: false,
IsLoggedIn: false,
});
return (
<AppContext.Provider value={{ appState, setAppState }}>
<View style={styles.container}>
<Text style={styles.paragraph}>{JSON.stringify(appState)}</Text>
<Button />
</View>
</AppContext.Provider>
);
}
class Button extends React.PureComponent {
render() {
return (
<TouchableOpacity
onPress={() =>
this.context.setAppState({
IsLoading: !this.context.appState.IsLoading,
IsLoggedIn: true,
})
}>
<Text>Update</Text>
</TouchableOpacity>
);
}
}
Button.contextType = AppContext;
零食网址 https://snack.expo.io/@guruparan/contextwithclass
添加回答
举报
