修复错误:路由“Home”的组件必须是React组件 [英] Fix Error: The component for route 'Home' must be a React component

查看:67
本文介绍了修复错误:路由“Home”的组件必须是React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用react-navigation,但是当我将每个屏幕的组件移动到多个文件中时,我无法使用它。我总是得到这个错误:路由'Home'的组件必须是React组件。如果我将所有代码移动到一个文件中,则不会发生此错误,所以我不确定区别是什么。

I'm trying to used react-navigation but I can not get it to work when I move each screens' components into multiple files. I always get this error: "The component for route 'Home' must be a React component". This error doesn't happen if I move all of the code into one file, so I'm not sure what the difference is.

这是我的App.js:

Here is my App.js:

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

import { HomeScreen } from './screens/HomeScreen';
import { JoinScreen  from './screens/JoinScreen';
import { HostScreen } from './screens/HostScreen';


const Root = StackNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
    Details: {
      screen: JoinScreen,
    }
  }, 
  {
    initialRouteName: 'Home',
    headerMode: 'none',
  }
);

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

这是我的.screens / HomeScreen.js

And here is my .screens/HomeScreen.js

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

export default class HomeScreen extends React.Component {
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Hello World</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'space-around',
  }
});


推荐答案

我想如果你改变这一行:

I think that if you change this line:

import { HomeScreen } from './screens/HomeScreen';

to:

import HomeScreen from './screens/HomeScreen';

(即删除 HomeScreen 周围的大括号)然后它会工作。因为您在 HomeScreen 组件的源文件中使用了 export default ,所以不需要 import 解构 C>。这是试图访问组件上名为 HomeScreen 的变量,该变量解析为 undefined 并导致您看到的错误。

(i.e. removing the braces around HomeScreen) then it will work. Because you used export default in the HomeScreen component's source file, you don't need the destructuring on the import. This is attempting to access a variable called HomeScreen on the component, which is resolving to undefined and causes the error you saw.

或者,您可以从导出默认默认 c>并保持 import 相同。我个人更喜欢删除大括号,因为代码看起来更干净。

Alternatively, you can remove the default from export default and keep the import the same. I personally prefer removing the braces as the code looks cleaner.

此行还有一个缺少的大括号:

There's also a missing closing brace on this line:

import { JoinScreen  from './screens/JoinScreen';

但我认为这是一个错字;)

But I assumed that was a typo ;)

这篇关于修复错误:路由“Home”的组件必须是React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆