如何通过Drawer Navigation传递用户输入获取的动态prop
实现方案
你当前是Drawer导航嵌套Stack导航的结构,有两种常用的实现路径,可根据你的业务复杂度选择:
方案1:路由参数透传(适合轻量场景,仅需要传递邮箱参数)
这种方式不需要引入额外依赖,适合仅需要共享少量用户信息的场景:
- 登录页跳转传参
在LoginScreen的登录验证通过逻辑中,跳转首页时携带邮箱参数:
// 登录验证成功后执行 this.props.navigation.navigate('Home', { userEmail: this.state.email })
- 参数全局注入到Stack导航
你定义的Stack导航作为Drawer的唯一子页面,可以直接把拿到的参数注入到所有栈页面的初始参数中:
// 你返回Stack.Navigator的Screens组件代码 const Screens = (props) => { // 从路由中取登录页传过来的邮箱 const userEmail = props.route.params?.userEmail; return ( <Stack.Navigator screenOptions={{ // 全局给所有栈页面注入初始参数 initialParams: { userEmail } }} > {/* 原有Stack.Screen代码不需要修改,你之前写的自定义props比如test="test"、{...navigation}不会生效,可删除 */} <Stack.Screen name="Home" component={Home} /> <Stack.Screen name="Book" component={Book} /> <Stack.Screen name="Login" component={LoginScreen} /> <Stack.Screen name="Sign Up" component={SignUp} /> <Stack.Screen name="CheckIn" component={CheckIn} /> <Stack.Screen name="Search" component={Search} /> </Stack.Navigator> ) }
- 任意页面取参数
不管是通过Stack跳转还是Drawer跳转,所有栈页面都可以直接从路由参数中拿到邮箱:
// 类组件写法 const userEmail = this.props.route.params?.userEmail;
方案2:全局状态管理(适合复杂场景,后续需要存储更多用户信息)
如果你的应用后续还要存储用户ID、token、头像等信息,用路由透传会非常繁琐,直接用全局状态更易维护,这里举React自带Context API的实现示例,不需要额外安装依赖:
- 新建全局上下文文件
UserContext.js:
import { createContext } from 'react'; export const UserContext = createContext(null);
- 根组件包裹上下文Provider:
// 你的App根组件代码 import { UserContext } from './UserContext'; class App extends React.Component { state = { userInfo: null } render() { return ( <UserContext.Provider value={{ userInfo: this.state.userInfo, setUserInfo: (info) => this.setState({userInfo: info}) }}> {/* 原有Drawer.Navigator代码保持不变 */} <Drawer.Navigator initialRouteName="Home" drawerType="slide" overlayColor="transparent" drawerStyle={styles.drawerStyles} contentContainerStyle={{flex: 1}} screenOptions={{ headerShown: false, activeBackgroundColor: 'transparent', activeTintColor: 'white', inactiveTintColor: 'white', }} sceneContainerStyle={{backgroundColor: 'transparent'}} drawerContent={props => <DrawerContent {...props} />}> <Drawer.Screen name="Screens"> {props => <Screens {...props} style={animatedStyle} />} </Drawer.Screen> </Drawer.Navigator> </UserContext.Provider> ) } }
- 登录成功后更新全局状态:
// LoginScreen组件中添加上下文声明 class LoginScreen extends React.Component { static contextType = UserContext; // 登录验证成功后执行 onLoginSuccess = () => { this.context.setUserInfo({ email: this.state.email }); this.props.navigation.navigate('Home'); } }
- 任意页面获取邮箱:
// 需要用到邮箱的页面添加上下文声明后直接取即可 class Book extends React.Component { static contextType = UserContext; render() { const userEmail = this.context?.userInfo?.email; // 后续业务逻辑 } }
如果需要持久化登录状态,你可以把用户信息存储到AsyncStorage中,应用启动时读取后更新到全局状态即可。
内容的提问来源于stack exchange,提问作者Vaibhav Herugu
相关产品推荐
相关产品推荐

