StackNavigator 通过 Component 给出未定义的错误

StackNavigator through Component gives undefined error

我试图使用 StackNavigator 进行导航,当我使用它从一个屏幕转到另一个屏幕时它可以正常工作 here。但是当我尝试让一个子组件自行导航时,导航似乎不起作用,我找不到任何解决方案。

如下面的代码所示,我正在尝试使用测试组件,其中有一个按钮可以单击以从主屏幕移动到聊天屏幕。

我很确定解决方案是基本的,但我真的找不到它。

这是我的代码:

import React from 'react';
import {
  AppRegistry,
  Text,
  View,
  Button
} from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    let userName = 'Ketan';
    return (
      <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat', { user: userName })}
          title={"Chat with " + userName}
        />
        <Test />
      </View>
    );
  }
}

class ChatScreen extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: `Chat with ${navigation.state.params.user}`,
  });
  render() {
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text>Chat with {params.user}</Text>
      </View>
    );
  }
}

class Test extends React.Component {
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Button
          onPress={() => navigate('Chat', { user: 'TestBot' })}
          title={'This is a test'}
        />
      </View>
    )
  }
}

const NavApp = StackNavigator({
  Home: { screen: HomeScreen },
  Chat: { screen: ChatScreen },
});

AppRegistry.registerComponent('NavApp', () => NavApp);

这是我遇到的错误:

这是要测试的演示:https://snack.expo.io/HyaT8qYob

我希望我的问题足够清楚我的意思。

由于您的 Test 组件不属于导航堆栈,因此它没有导航道具。你可以做几件事。

简单的一种是将导航传递给子组件,如下例所示。

return (
  <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat', { user: userName })}
          title={"Chat with " + userName}
        />
        <Test navigation={this.props.navigation} />
      </View>
);

第二个选项是,您可以使用 react-navigation 中的 withNavigation。您可以找到有关它的更多详细信息 here

import { Button } 'react-native';
import { withNavigation } from 'react-navigation';

const MyComponent = ({ to, navigation }) => (
    <Button title={`navigate to ${to}`} onPress={() => navigation.navigate(to)} />
);

const MyComponentWithNavigation = withNavigation(MyComponent)

withNavigation

withNavigation is a higher order component which passes the navigation prop into a wrapped component. It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child.