Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

javascript - Fix Error: The component for route 'Home' must be a React component

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.

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 />
    )
  }
}

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',
  }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think that if you change this line:

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

to:

import HomeScreen from './screens/HomeScreen';

(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.

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 ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...