You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何将sign.js的userInfo传递至Signupfor.js?

问题描述

我有一个名为baby_login的父组件文件,其中包含一个名为Sign的谷歌注册按钮组件。当点击该按钮时,我希望将sign.js中的userInfo传递给Signupfor.js,请问该如何实现?


解决方案

我们可以通过React Navigation的跳转传参结合组件props传递来实现需求,具体步骤如下:

步骤1:给Baby_login组件传递navigation并传给Sign组件

首先让Baby_login(导航中对应Baby组件)接收navigation对象,再将其传递给Sign组件:

// baby_login组件修改后
export default function Baby_login({ navigation }) {
  return (
    <View style={styles.prheight}>
      <Image
        source={require('../assets/images/mother.png')}
        style={{
          width: 300,
          marginLeft: 20,
          marginTop: 0,
          justifyContent: 'center',
          height: 300,
          textAlign: 'center',
        }}
      />
      <View style={styles.buttonw}>
        <Sign navigation={navigation} /> {/* 传递navigation给Sign */}
      </View>
    </View>
  );
}

步骤2:修改Sign组件,登录成功后跳转传参

修正Sign组件的参数接收方式,在谷歌登录成功后,通过navigation.navigate跳转到Signupfor页面并携带userInfo:

// sign.js组件修改后
import React from 'react';
import { View } from 'react-native';
import { GoogleSignin, GoogleSigninButton } from '@react-native-google-signin/google-signin';

export default function Sign({ navigation }) {
  async function onGoogleButtonPress() {
    try {
      await GoogleSignin.hasPlayServices();
      const userInfo = await GoogleSignin.signIn();
      console.log(userInfo);
      // 跳转并传递userInfo
      navigation.navigate('Signupfor', { userInfo });
    } catch (error) {
      console.error('登录失败:', error);
    }
  }

  return (
    <View style={styles.prheight}>
      <View style={styles.buttonw}>
        <GoogleSigninButton
          style={{width: 192, height: 48}}
          size={GoogleSigninButton.Size.Wide}
          color={GoogleSigninButton.Color.Light}
          onPress={onGoogleButtonPress}
        />
      </View>
    </View>
  );
}

注:需确保已完成谷歌登录的依赖安装与初始化配置,此处省略该部分代码。

步骤3:修改Signupfor组件接收并使用userInfo

从route.params中获取传递的userInfo,并做空值处理避免报错:

// Signupfor.js组件修改后
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function Signupfor({ route }) {
  const { userInfo } = route.params || {};

  return (
    <View style={styles.prheight}>
      {userInfo && (
        <View>
          <Text>用户邮箱:{userInfo.user.email}</Text>
          <Text>用户姓名:{userInfo.user.name}</Text>
          {/* 可根据需求展示更多用户信息 */}
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  prheight: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

额外提示

如果需要在多个组件间共享userInfo,可以使用React Context或Redux做全局状态管理,避免频繁的参数传递。


内容的提问来源于stack exchange,提问作者vivek kn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:15:36