首页 > 解决方案 > 如何修复 React-Native 中的“路由 'Principal' 的组件必须是 React 组件”错误

问题描述

我是 react-native 的新手,遇到了这个问题:( 路由“Principal”的组件必须是 React 组件。例如:...)

我想在 StackNavigator 中放置一个 DrawerNavigator。我已经看到这是一个好方法,但它给了我一直在寻找的这个错误,但我无法解决它。

谢谢

应用程序.js

import React, { Component } from 'react';
import {createAppContainer,createStackNavigator,createDrawerNavigator} from 'react-navigation';
import Login from './pantallas/login';
import Registro from './pantallas/registro';
import PantallaPrincipal from './pantallas/pantallaPrincipal';
import SolicitudCitas from './pantallas/socitudCitas';
import {Header,Icon} from 'native-base';

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

const AppStackNavigator = createStackNavigator({
  Login: { screen: Login },
  Registro: { screen: Registro },
  Principal: {screen: AppDrawerNavigator}
},{
  headerMode: 'none',
  navigationOptions: {
    headerVisible: false,
  }
}
);

const AppDrawerNavigator = createDrawerNavigator({
    PantallaPrincipal:{screen: PantallaPrincipal},
    SolicitudCitas: {screen: SolicitudCitas}}
    ,{
    defaultNavigationOptions: ({ navigation }) => {
        return {
          headerLeft: (
            <Header>
              <Icon
                style={{ paddingLeft: 10 }}
                onPress={() => navigation.openDrawer()}
                name="menu"
                size={30}/>
            </Header>
          )
        };
      }
    }
  );

const AppContainer = createAppContainer(AppStackNavigator);

pantallaPrincipal.js

import React, { Component } from 'react';
import { Text, View,StyleSheet } from 'react-native';

export default class pantallaPrincipal extends Component {
    
  render() {
    return (
      <View style={styles.backgroundContainer}>
        <Text>Pantalla principal</Text>
      </View>
    );
  }
}


const styles = StyleSheet.create({
  backgroundContainer : {
    flex: 1,
    width: null,
    height: null,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

solicitudCitas.js

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class solicitudCitas extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Solicitud Citas</Text>
      </View>
    );
  }
}

标签: react-native

解决方案


只需在您使用它的堆栈导航器上方声明和初始化您的 DrawerNavigator。这只是由于 JS 的提升基础而发生的。在 javascript 中,只有声明被提升,而不是初始化,所以当你使用时Principal: {screen: AppDrawerNavigator},JS 不知道它AppDrawerNavigator实际上是一个 React 组件,因为它在使用之前没有被初始化。你可以在这里学习更多关于 JS 提升的知识。


推荐阅读