[RN Log] React-Native Getting Started Guide

1. Background

1. Why do we need React-Native?

Before the emergence of React-Native, the mainstream mobile development model was native development and Hybrid development (H5 hybrid native development). The advantage of Hybrid app compared to native app is that the development cost is low and the development speed is fast (H5 page development is cross-platform, no need to re Write web, android, ios code), although native app needs more time to develop, but it brings a better user experience (page rendering, the smoothness of gesture operation), it is also based on these two points. Launched React-Native in 2015

What we really want is the user experience of the native mobile
platforms, combined with the developer experience we have when
building with React on the web.

The above is taken from the React-Native release. The development of React-Native not only retains the development efficiency of React but also has a user experience comparable to native. Its operating principle is not using webview, so it is not Hybrid development. If you want to know, you can check the operating principle of React Native. Parse this article. The concept of React-Native is'learn once, write every where'. The reason why it is not'learn once, run every where' is because the user experience of different platforms is different. Therefore, to run the whole platform, some additional adaptations are still needed. With, here is Occhino's introduction to React-Native.
React-Native's number of stars on Github
React-Native's npm downloads
The above two pictures show the popularity of React-Native for developers, and its official development status has been updated, which is also an important factor in its ability to seize the native development market.

Second, build a development environment

Before creating a project, we need to build the development environment required by React-Native.
The first step is to install nodejs, python2, jdk8 (windows are different, it is recommended to use macos development, easy and convenient)

brew install node //macos comes with python and jdk

The second step is to install React Native CLI

npm install -g react-native-cli

The third step is to install Android Studio, refer to the official development document

Three, create the first application

Use the react-native command to create a project called HelloReactNative

react-native init HelloReactNative

After waiting for it to download related dependencies, run the project

react-native run-ios
or
react-native run-android

The interface that appears after successful operation is like this

react-native-helloworld.png

Four, basic JSX and ES6 syntax

Let's take a look at the interface code after successful operation

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

const instructions = Platform.select({
    
    
    ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
    android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

//noinspection BadExpressionStatementJS
type
Props = {
    
    };
//noinspection JSAnnotator
export default class App extends Component<Props> {
    
    
    render() {
    
    
        return (
            <View style={
    
    styles.container}>
                <Text style={
    
    styles.welcome}>
                    Welcome to React Native!
                </Text>
                <Text style={
    
    styles.instructions}>
                    To get started, edit App.js
                </Text>
                <Text style={
    
    styles.instructions}>
                    {
    
    instructions}
                </Text>
            </View>
        );
    }
}

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

The code appears in import, export, extends, classand does not appear () => arrow functions are ES6 need to know basic grammar, importexpressed the need to introduce modules exportrepresent export module, extendsexpressed inherited from a parent class, classit represents the definition of a class, ()=>is Arrow functions, functions defined with this grammar carry context information, so there is no need to deal with the issue of this reference.
<Text style={styles.welcome}>Welcome to React Native!</Text>This code is the way to use the JSX syntax, which is the same as the HTML markup language, except that the component of React-Native is quoted here, which Textis a component that displays text. You can see that style={styles.welcome}this is another syntax of JSX that can express valid js. The formula is placed in curly brackets as Welcome to React Native!its content text. You can try to modify its content to be familiar with more ES6 syntax Hello React Native!after refreshing the interface, which
Insert picture description here
will help more efficient development.

Five, the attributes and status of the component

After understanding some basic JSX and ES6 syntax, we also need to understand two more important concepts, namely propssum state, which propsis the attribute stateof the component, and the state of the component. The difference between the two is that it propswill pass when the component is instantiated. The construction parameters are passed in, so propsthe transmission is one-way, and can only be controlled by the parent component, and statethe internal state of the component is managed by the component itself and is not affected by the outside world. Both propsand statecan modify the state of the component. The change of the two will cause the state of the related referenced component to change. That is to say, there are sub-components in the component that reference the propssum state, then when the change occurs, the corresponding sub-component will be re-rendered. In fact, it is also here. It can be seen that in connection propswith statethe use of and, the parent component can be setStatemodified stateand passed to the child component to propsre-render the child component so that the parent component re-renders.

Six, component life cycle

Insert picture description here
The life cycle of a component will go through three stages

Mounting:挂载
Updating:更新
Unmounting:移除

The corresponding life cycle callback method is

componentWillMount()//组件将要挂载时调用
render()//组件渲染时调用
componentDidMount()//组件挂载完成时调用
componentWillReceiveProps(object nextProps)//组件props和state改变时调用
shouldComponentUpdate(object nextProps,object nextState)//返回false不更新组件,一下两个方法不执行
componentWillUpdate(object nextProps,object nextState)//组件将要更新时调用
componentDidUpdate(object nextProps,object nextState)//组件完成更新时调用
componentWillUnmount()//组件销毁时调用

Here we need to focus on the stage of component operation. The render()method is called every time the component status is updated . Unless the shouldComponentUpdatemethod returns false, this method can be used to optimize the component to avoid the performance consumption caused by repeated rendering.

The style
React-Nativestyle implements a subset of CSS. The properties of the style are slightly different from CSS. Its naming adopts the camel case name, which is basically the same for front-end developers. The method of use is also very simple, first use StyleSheet to create onestyles

const styles = StyleSheet.create({
    
     
    container:{
    
    
        flex:1
    }
})

Then pass the corresponding attributes styleto the component style, for example<View style={styles.container}/>

Seven, common components

Components most commonly used in daily development than View, Text, Image, TextInputcomponents.

ViewSubstantially as a container arrangement, which can be placed in a variety of controls, generally only need to set a styleproperty to, style attributes are used flex, width, height, backgroundColor, flexDirector, margin, paddingMore to view Layout Props.

TextIt is a control that displays text. You only need to fill in the text content in the content area of ​​the component. For example <Text>Hello world</Text>, you can set the font size and color <Text style={ {fontSize:14,color:'red'}}>Hello world</Text>, and also support nesting Text, such as

<Text style={
    
    {
    
    fontWeight: 'bold'}}>
        I am bold
        <Text style={
    
    {
    
    color: 'red'}}>
          and red
        </Text>
</Text>

TextInputIt is a text input box control, and its use is also very simple

<TextInput
     style={
    
    {
    
    width:200,height:50}}
     onChangeText={
    
    (text)=>console.log(text)}
/>

styleSet his style and onChangeTextpass in a method that will be called when the text in the input box changes. Here we use console.log(text)the text in the print input box.

ImageIt is a picture control. Almost all apps will use pictures as their personalized display. ImageYou can load local and network pictures. When loading network pictures, you must set the size of the control, otherwise the pictures will not be displayed.

加载本地图片,图片地址为相对地址
<Image style={
    
    {
    
    width:100,height:100}} source={
    
    require('../images/img001.png')}/>
加载网络图片
<Image style={
    
    {
    
    width:100,height:100}} source={
    
    {
    
    uri:'https://facebook.github.io/react-native/docs/assets/favicon.png'}}/>

Guess you like

Origin blog.csdn.net/u013034585/article/details/106242866