开发者问题收集

在 react-navigation 中通过 onPress() 传递对象参数

2020-06-18
178

我尝试通过 PlanScreen 中的 onPress() 将对象参数传递给 PlanDetailScreen,但出现错误“TypeError;undefined 不是对象(评估‘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个回答

穆罕默德 说的是对的,但你还必须考虑到导航参数来自屏幕的 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/

Kevin Gelpes
2020-06-19

您正在覆盖 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>
      )}
    />
  );
}
MUHAMMAD ILYAS
2020-06-19