在反应导航中通过onPress()传递对象参数

时间:2020-06-18 23:57:38

标签: react-native react-navigation react-router-dom

我尝试通过PlanScreen中的onPress()将对象参数传递给PlanDetailScreen,但是错误发生为'TypeError;未定义不是对象(评估“ detail.weekNumber”)。 如何解决?

function PlanDetailScreen({ detail }) {
  return (
    <SafeAreaView>
      <Text key={detail.weekNumber}>{"Week " + detail.weekNumber}</Text>
    </SafeAreaView>
  );
}

function PlanScreen({ navigation }) {
  return (
    <FlatList
      numColumns={5}
      data={PlanData}
      renderItem={({ detail }) => (
        <TouchableOpacity
          onPress={(detail) =>
            navigation.navigate("PlanDetailScreen", { detail })
          }
        >
          <Text key={detail.weekNumber}>{"Uke\n" + detail.weekNumber}</Text>
        </TouchableOpacity>
      )}
    />
  );
}

2 个答案:

答案 0 :(得分:0)

您正在覆盖detail,这就是为什么未定义详细信息的原因,只需将其从onPress中删除

function PlanDetailScreen({ detail }) {
  return (
    <SafeAreaView>
      <Text key={detail.weekNumber}>{"Week " + detail.weekNumber}</Text>
    </SafeAreaView>
  );
}

function PlanScreen({ navigation }) {
  return (
    <FlatList
      numColumns={5}
      data={PlanData}
      renderItem={({ detail }) => (
        <TouchableOpacity
          onPress={() =>
            navigation.navigate("PlanDetailScreen", { detail })
          }
        >
          <Text key={detail.weekNumber}>{"Uke\n" + detail.weekNumber}</Text>
        </TouchableOpacity>
      )}
    />
  );
}

答案 1 :(得分:0)

Muhammad said是正确的,但是您还必须考虑到导航参数出现在屏幕的route道具中。

它看起来像这样:

function PlanDetailScreen({ route }) {
  return (
    <SafeAreaView>
      <Text key={detail.weekNumber}>{"Week " + route.params.detail.weekNumber}</Text>
    </SafeAreaView>
  );
}

function PlanScreen({ navigation }) {
  return (
    <FlatList
      numColumns={5}
      data={PlanData}
      renderItem={({ detail }) => (
        <TouchableOpacity
          onPress={() =>
            navigation.navigate("PlanDetailScreen", { detail })
          }
        >
          <Text key={detail.weekNumber}>{"Uke\n" + detail.weekNumber}</Text>
        </TouchableOpacity>
      )}
    />
  );
}

看看: https://reactnavigation.org/docs/params/