【问题标题】:Create a navigation button with a props using react-navigation in React Native在 React Native 中使用 react-navigation 创建一个带有 props 的导航按钮
【发布时间】:2021-05-27 13:54:15
【问题描述】:

我正在尝试创建一个可以帮助我在堆栈之间导航的组件 Button。我使用 react-navigation 在应用程序中导航。问题是我有 3 个文件:

-App.js

<SafeAreaProvider>
  <StatusBar barStyle="dark-content" backgroundColor="#ecf0f1" />
  <NavigationContainer>
    <Stack.Navigator initialRouteName="Accueil">
      <Stack.Screen name="Accueil" component={AccueilScreen} options={{headerShown: false}}/>
      <Stack.Screen name="Progression" component={ProgressionScreen} />
      <Stack.Screen name="Themes" component={ThemesScreen} />
      <Stack.Screen name="Quizz" component={QuizzScreen} />
    </Stack.Navigator>
  </NavigationContainer>
</SafeAreaProvider>

-Accueil.js

function Accueil({ navigation }) {
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content_container}>
        <Image style={styles.logo} source={require('../assets/logo.jpg')} />
        <Button buttonText="Progression" navigation={navigation}/>
      </View>
   </SafeAreaView>
  )
}

-Button.js

export default function Button(props, navigation) {
  return (
    <TouchableOpacity style={styles.button} onPress={() => navigation.navigate(props.buttonText)}>
      <Text style={styles.button_text}>{props.buttonText}</Text>
    </TouchableOpacity>
  )
}

我的问题是我无法让 navigation.navigate 在 Button 组件中工作,而当我将它直接放在 Accueil.js 文件中时它完全可以工作。

你能帮帮我吗?

【问题讨论】:

    标签: javascript react-native react-navigation


    【解决方案1】:

    navigationprops 的一部分,来自您的 Button 组件

    export default function Button({ navigation, ...props }) {
      return (
        <TouchableOpacity style={styles.button} onPress={() => navigation.navigate(props.buttonText)}>
          <Text style={styles.button_text}>{props.buttonText}</Text>
        </TouchableOpacity>
      )
    }
    

    你也可以这样做:

    export default function Button(props) {
      const { navigation } = props
      ...rest of your code
    

    【讨论】:

    • 非常感谢,它有效!当我试图将它放在大括号内时,我错过了道具前的 3 个小点。您能告诉我添加这些点的名称是什么,以便我了解更多信息吗?
    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多