如何在常量中使用反应导航?

Ali*_*eza 2 reactjs react-native react-native-navigation react-navigation

我使用 const 来显示组件。现在,当我对 const 中的按钮使用反应导航时,我看到了这个错误:未定义不是一个对象(评估 '_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>
);
Run Code Online (Sandbox Code Playgroud)

库链接:http : //github.com/react-native-community/react-native-tab-view

Rob*_*zak 5

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

主要区别之一是 SFC 不会自动接收 props,而是必须作为参数传递。因此,与其说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>
);
Run Code Online (Sandbox Code Playgroud)

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

<WomenTab myProp={value} />
Run Code Online (Sandbox Code Playgroud)

另一种常见模式是解构传递给 SFC 的道具,如下所示:

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>
);
Run Code Online (Sandbox Code Playgroud)

希望能帮到你,祝你好运!