【问题标题】:Passing data from one screen to another screen with react-navigation使用反应导航将数据从一个屏幕传递到另一个屏幕
【发布时间】:2020-06-14 13:24:40
【问题描述】:

我目前正在将数据传递给react-native 中的一个组件,其中一些代码如下所示:

class Login extends Component {
  signInWithGoogle = async () => {
    try {
      const result = await Google.logInAsync({
        iosClientId: IOS_CLIENT_ID,
        androidClientId: ANDROID_CLIENT_ID,
        scopes: ["profile", "email"]
      });

      if (result.type === "success") {
        console.log(
          "LoginScreen.js.js 21 | ",
          result.user.givenName,
          result.user.familyName,
          result.user.email,
          result.user.photoUrl
        );
        this.props.navigation.navigate(
          "MyDrawer",
          (username = result.user.givenName),
          (lastname = result.user.familyName),
          (email = result.user.email),
          (photoUrl = result.user.photoUrl)
        );
        return result.accessToken;
      } else {
        return { cancelled: true };
      }
    } catch (e) {
      console.log("LoginScreen.js.js 30 | Error with login", e);
      return { error: true };
    }
  };
}

我的问题是如何将数据传递给不同的组件?

【问题讨论】:

  • 什么是数据以及在哪里被传递到任何组件?请附上您的代码的Minimal and Complete 示例以及您的问题所在。
  • 数据是从google的API中获取的。它获取姓名、姓氏、电子邮件和 photoURI。传递数据的 sn-p 在this gist snippet 中命名为 dataPassing.js。然后我使用 Drawer.js 中的数据,我想以某种方式将相同的数据传递给 QR.js 所有 3 个文件的代码和小 sn -p 在 Login.js 中扮演数据传递的角色是要点
  • 啊,我明白了,看来您至少是通过导航操作将它传递给某个组件,而您在问如何将它传递给另一个组件?当前组件(被导航到的组件)与此第三个组件之间的关系是什么?
  • Login.js 通过底部的 StackNavigation 调用 MyDrawer.js。当您按下按钮并完成登录时,该函数会将您发送到 MyDrawer.js,它会呈现包含第三个组件 QR.js 的 DrawerNavigation(您可以看到这个Drawer.js 文件底部的抽屉导航)

标签: reactjs react-native react-navigation


【解决方案1】:

您需要将对象作为第二个参数传递给 props 中的导航方法。 要将数据传递给不同的组件,请提供一个对象作为导航函数的第二个参数

改变这个

 this.props.navigation.navigate(
          "MyDrawer",
          (username = result.user.givenName),
          (lastname = result.user.familyName),
          (email = result.user.email),
          (photoUrl = result.user.photoUrl)
        );

到

 this.props.navigation.navigate("MyDrawer",{
  name: result.user.givenName,
  lastname : result.user.familyName,
  email :result.user.email,
  photoUrl = result.user.photoUrl
});

现在在你将数据传递到的组件中,你可以使用 react-navigation 的 getKey 方法获取键

TargetComponent.js

render() {
    email = this.props.navigation.getParam("email", defaultValue);
  password= this.props.navigation.getParam("password", defaultValue);
}


【讨论】:

  • 这不起作用。我正在使用 React Navigation 5 和 Hooks。 Drawer.js 和 QR.js(目标组件)都是函数,而不是类。
  • 您可以通过 useNavigation 访问导航:reactnavigation.org/docs/use-navigation
  • 这样做this way 给我一个错误不变的违规:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。
猜你喜欢
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
  • 2018-12-30
  • 2022-12-07
相关资源
最近更新 更多