React Navigation 7 Static API中如何用Context包裹嵌套导航器
要实现只让 ProfileStack 内的屏幕访问 ProfileContext,同时不让 HomeScreen 访问,你需要把 ProfileStackNavigator 用 ProfileProvider 包裹成独立组件,再传入 RootStack 的配置中。具体修改如下:
修改步骤
- 不再直接将
ProfileStackNavigator作为 RootStack 的 screen,而是创建一个包裹了ProfileProvider的组件 - 在该组件内部渲染
ProfileStackNavigator
修改后的完整代码
// Screens function HomeScreen() { const navigation = useNavigation(); return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <Text>Home Screen</Text> <Button title="Show Profile modal" onPress={() => navigation.navigate('ProfileStack')} /> </View> ); } function ProfileScreen() { const navigation = useNavigation(); // 现在可以在这里使用 ProfileContext 了 const { name, setName } = React.useContext(ProfileContext); return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <Text>Profile: {name || '未设置'}</Text> <Button title="设置名字" onPress={() => setName('Test Name')} /> <Button title="Go to More Profile" onPress={() => navigation.navigate('ProfileStack', {screen: 'MoreProfile'}) } /> </View> ); } function MoreProfileScreen() { // 这里也能访问 ProfileContext const { name } = React.useContext(ProfileContext); return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <Text>More Profile: {name || '未设置'}</Text> </View> ); } // Context type ProfileContextType = { name?: string; setName: (name: string) => void; }; const ProfileContext = React.createContext<ProfileContextType | undefined>( undefined, ); const ProfileProvider = ({children}: {children: React.ReactNode}) => { const [name, setName] = React.useState<string>(); return ( <ProfileContext.Provider value={{name, setName}}> {children} </ProfileContext.Provider> ); }; // Navigators const ProfileStackNavigator = createNativeStackNavigator({ screens: { Profile: ProfileScreen, MoreProfile: MoreProfileScreen, }, }); // 新增:用 ProfileProvider 包裹 ProfileStackNavigator const ProfileStackWithProvider = () => { return ( <ProfileProvider> <ProfileStackNavigator /> </ProfileProvider> ); }; const RootStackNavigator = createNativeStackNavigator({ screens: { Home: HomeScreen, ProfileStack: { // 这里改为使用包裹后的组件 screen: ProfileStackWithProvider, options: { presentation: 'modal', headerShown: false, }, }, }, }); const Navigation = createStaticNavigation(RootStackNavigator); // App function App(): React.JSX.Element { return <Navigation />; } export default App;
说明
- 新增的
ProfileStackWithProvider组件将ProfileStackNavigator包裹在ProfileProvider内部,确保只有该栈内的屏幕能访问 Context - HomeScreen 不在这个 Provider 的范围内,因此无法访问 ProfileContext
- 你可以在 ProfileScreen 和 MoreProfileScreen 中正常使用
useContext(ProfileContext)获取状态和方法
内容的提问来源于stack exchange,提问作者Wiingaard
相关产品推荐
相关产品推荐

