在本机反应中将数据传递到其他屏幕

dav*_*des 3 reactjs react-native expo

我想出了如何在第一个屏幕中使用 navigation.navigate(screenName, {variables I Want to pass through}) 和 const {variables I Want to pass down} = route.params on React Native 将数据从一个屏幕传递到另一个屏幕另一个屏幕。

但是,如果我想将同一变量从屏幕二传递到屏幕三怎么办?我尝试做与从屏幕一到屏幕二相同的操作,但我得到了“对象是“我想要传递的变量”的未定义错误。这是传递变量的错误方法吗?请告诉我。

小智 9

我有id= 5,我想将它从 ScreenA 传递到 ScreenB,然后将 ScreenB 传递到 ScreenC,下面(也许)是useRoute的最简单示例:

import { useRoute } from "@react-navigation/native"
Run Code Online (Sandbox Code Playgroud)

ScreenA

function ScreenA({ navigation }) {
  return (
    <Button
      title="Go to ScreenB"
      onPress={() => navigation.navigate("ScreenB", { id: 5 })}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

ScreenB

function ScreenB({ navigation }) {
  const route = useRoute()
  const id = route.params?.id
  return (
    <Button
      title="Go to ScreenC"
      onPress={() => navigation.navigate("ScreenC", { id })}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

ScreenC

function ScreenC({ navigation }) {
  const route = useRoute()
  const id = route.params?.id
  return (
    <Text>{id}</Text>
  );
}
Run Code Online (Sandbox Code Playgroud)

idScreenC中就是你需要的id。