如何在const中使用反应导航?

问题描述 投票:2回答:3

我用const来显示组件。现在当我对const中的按钮使用反应导航时,我看到了这个错误:undefined不是一个对象(评估'_this.props.navigation.navigate')

我尝试将navigation = {this.props.navigation}添加到按钮以允许导航,但没有奏效。

const WomenTab = () => (
    <View>
      <Button onPress={() => {
                        this.props.navigation.dispatch(StackActions.reset({
                          index: 0,
                          actions: [
                            NavigationActions.navigate({ routeName: 'Wallet' })
                          ],
                        }))
                      }}>
          <Text>Click</Text>
      </Button>
    <View>
);

图书馆链接:http://github.com/react-native-community/react-native-tab-view

reactjs react-native react-navigation react-native-navigation
3个回答
4
投票

这被称为functional component,通常被称为无状态功能组件。

其中一个主要区别是SFC不会自动接收道具,而是必须作为参数传递。因此,不要说this.props你应该使用这种模式:

const WomenTab = (props) => ( // <-- add props as an argument
  <View>
    <Button onPress={() => {
      props.navigation.dispatch(StackActions.reset({
        index: 0,
        actions: [ NavigationActions.navigate({ routeName: 'Wallet' }) ],
      }))
    }}>
      <Text>Click</Text>
    </Button>
  <View>
);

由于导航道具会自动传递给导航员的子项,因此您无需执行任何其他操作。如果你想传递其他道具,你会像往常一样:

<WomenTab myProp={value} />

另一个常见的模式是destructure传递给SFCs的道具如下:

const WomenTab = ( {navigation} ) => ( // <-- you can pick the props you want via destructuring
  <View>
    <Button onPress={() => {
      navigation.dispatch(StackActions.reset({
        index: 0,
        actions: [ NavigationActions.navigate({ routeName: 'Wallet' }) ],
      }))
    }}>
      <Text>Click</Text>
    </Button>
  <View>
);

希望有所帮助,祝你好运!


1
投票

你需要将你的props传递给const,就像这样

const WomenTab = (props) => (
    <View>
      <Button onPress={() => {
                        props.navigation.dispatch(StackActions.reset({
                          index: 0,
                          actions: [
                            NavigationActions.navigate({ routeName: 'Wallet' })
                          ],
                        }))
                      }}>
          <Text>Click</Text>
      </Button>
    <View>
);

然后当你使用你的const时,你会传递你想要的道具。

<WomenTab navigation={this.props.navigation} />

1
投票

基本上你的道具没有从父组件传递到子组件。确保已在createStackNavigator函数中定义了WomenTab组件。还可以在函数组件中传递道具。

const WomenTab = (props) => (
<View>
  <Button onPress={() => {
                    this.props.navigation.dispatch(StackActions.reset({
                      index: 0,
                      actions: [
                        NavigationActions.navigate({ routeName: 'Wallet' })
                      ],
                    }))
                  }}>
      <Text>Click</Text>
  </Button>
<View>

);

© www.soinside.com 2019 - 2024. All rights reserved.