const App: () => React$Node = () => {…}: what does

2020-05-25 02:56发布

问题:

on react-native init ProjectName, the main app file App.js contains the declaration of a component in the following way:

const App: () => React$Node = () => {...}

What does it mean this instruction?

I mean, I'm used to component defined as const App = () => {...}, so I don't understand, in particular, the expression in between: () => React$Node.

回答1:

Its type definition from Flow, it means that constant App is of type function and it returns ReactNode.

ReactNode is one of these types: ReactChild | ReactFragment | ReactPortal | boolean | null | undefined

This means the function App can return, any valid JSX (in react native its anything from View, Text, .etc), ReactFragment, React.Portal, boolean, null, undefined

If you are confused about the dollar sign, here is a link with explanation. https://www.saltycrane.com/flow-type-cheat-sheet/latest/

There are separate sections for "private" or "magic" types with a $ in the name. See the note here and comment here. Update: Some these types are now documented here.

For easy you can think of it as its Node from React (think of it as scope/namespace)



回答2:

It is also a type of declaration of App component as a function but you can change it to

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

export default class App extends Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.instructions}>Hello World!</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5
    }
});

Don't forget to remove statement Export default App in the last line.



回答3:

React$Node is a type defined in react.js

declare type React$Node =
  | null
  | boolean
  | number
  | string
  | React$Element<any>
  | React$Portal
  | Iterable<?React$Node>;