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

2020-05-25 02:38发布

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.

3条回答
干净又极端
2楼-- · 2020-05-25 03:17

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楼-- · 2020-05-25 03:20

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)

查看更多
Evening l夕情丶
4楼-- · 2020-05-25 03:21

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>;
查看更多
登录 后发表回答