找不到变量:react原生中的“导航”

3z6pesqy  于 2023-02-13  发布在  React
关注(0)|答案(2)|浏览(151)

这是我的代码,我用了一些从youtube。

import React from "react";
import { View, Button, StyleSheet, TouchableOpacity, Text } from "react-native";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

// touchableOpacity makes the button

const AppButton = ({ onPress, title }) => (
  <TouchableOpacity
    onPress={() => navigation.navigate("SignInScreen")}
    style={styles.appButtonContainer}
  >
    <Text style={styles.appButtonText}>{title}</Text>
  </TouchableOpacity>
);

// Navigation should lead to SignInScreen

const App = ({ navigation }) => {
  return (
    <View style={styles.screenContainer}>
      <AppButton title="Register" size="sm" backgroundColor="#007bff" />
    </View>
  );
};

// Styling Button and everything

const styles = StyleSheet.create({
  screenContainer: {
    flex: 1,
    justifyContent: "flex-end",
    padding: 16,
  },
  appButtonContainer: {
    elevation: 8,
    backgroundColor: "#009688",
    borderRadius: 10,
    height: 60,
    paddingVertical: 10,
    paddingHorizontal: 12,
  },
  appButtonText: {
    fontSize: 30,
    color: "#fff",
    fontWeight: "bold",
    alignSelf: "center",
    textTransform: "uppercase",
  },
});

export default App;
zfciruhq

zfciruhq1#

它也需要AppButton中的导航对象。我可以看到您将导航对象作为 prop 传递给了App。但是,我在AppButton中没有看到它。

const AppButton = ({ onPress, title,navigation }) => (

      <TouchableOpacity onPress={()=>navigation.navigate('SignInScreen') style={styles.appButtonContainer}>
        <Text style={styles.appButtonText}>{title}</Text>
      </TouchableOpacity>

 );
slmsl1lt

slmsl1lt2#

您似乎没有从任何地方声明或导入navigation
但是假设你使用的是react-navigation,你应该使用useNavigation钩子,如下所示:

import { useNavigation } from "@react-navigation/native";

const AppButton = ({ onPress, title }) => {
    const navigation = useNavigation();

    return (
        <TouchableOpacity onPress={() => navigation.navigate('SignInScreen')} style=
            {styles.appButtonContainer}>
            <Text style={styles.appButtonText}>{title}</Text>
        </TouchableOpacity>
    );
};

这也得益于在必须将 prop 传递给不同组件时减少混乱。

相关问题