首页 > 解决方案 > 从另一个文件导入类后,React Navigation Switch Navigator 不起作用

问题描述

嗨,请在此处查看我的代码:

https://snack.expo.io/@ersimransingh/navigation-problem

我创建了我的切换导航器以在从 App.js 到 Second.js 的页面之间导航

在 App.js 页面上,我导入了名为 App1 的 Second.js 文件模块,该模块工作文件。

此外,我对 Second.js 文件从 App.js 导入的 App 组件做了同样的事情但是页面上的 swith navigator show error 说

路由“App”的组件必须是 React 组件。

我确实在互联网上搜索过相同的内容,并尝试从 import {App} from './App' 替换我的重要语法;从 './App' 导入 App;

您可以在博览会上查看我的代码 https://snack.expo.io/@ersimransingh/navigation-problem

标签: javascriptreact-nativereact-navigation

解决方案


您有 App.js 正在使用 Second.js 创建路由,而 Second.js 正在使用 App.js 创建路由。这绝对是有问题的,因为您正在创建一个循环引用。相反,您应该在一个地方创建导航并在 App.js 中使用它

这是一个示例:App.js

  export default class App extends React.Component{
      render(){
        return(
          <CreateTag />
        );
      }
    }

const AppContainer = createSwitchNavigator({
  FirstScreen,
  SecondScreen 
});

const CreateTag = createAppContainer(AppContainer);

FirstScreen.js

    export default class FirstScreen extends React.Component {
      render() {
        let { navigation } = this.props;

        return (
          <View>
            <Text
              style={styles.sampleText}
              onPress={() => navigation.navigate('SecondScreen')}>
              First screen
            </Text>
          </View>
        );
      }
    }

SecondScreen.js

export default class SecondScreen extends React.Component {
  render() {
    let { navigation } = this.props;

    return (
      <View>
        <Text
          style={styles.sampleText}
          onPress={() => navigation.navigate('FirstScreen')}>
          Second screen
        </Text> 
      </View>
    );
  }
}

这是完整的示例:https ://snack.expo.io/S1cY9IVEV 您也可以查看官方示例:https ://github.com/react-navigation/react-navigation/blob/master/examples/NavigationPlayground/ js/App.js

我希望这有帮助。


推荐阅读