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
添加回答
舉報