Mid-Autumn Festival at home idle, thinking about doing something, later thought, why not learn react Native. When learning React Native, you need to know the front end (HTML, CSS, JavaScript). For JS, check out Ruan Yifeng’s introduction to ECMAScript 6. It covers a lot of new ES6 features. I also read Teacher Ruan’s article before and made some study notes ES6 study notes.

1. Environment construction

Environment to build Chinese tutorial, click on the jump RN Chinese communities: reactnative. Cn/docs / 0.40 / g…

Community content is very detailed, we follow the operation step by step, encounter problems, baidu directly. Also check out this article: The React Native Pothole Filling Guide will show you how to fill potholes flat.

React Native Basics

First take a look at an example, this address source address: example tutorial: movie list. This example was chosen because it covers almost all the basics of getting started with React Native.

import React, { Component } from "react"; import { Image, FlatList, StyleSheet, Text, View } from "react-native"; Var REQUEST_URL = "https://raw.githubusercontent.com/facebook/react-native/0.51-stable/docs/MoviesExample.json"; export default class SampleAppMovies extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false }; // In ES6, if you use the this keyword in a custom function, you need to "bind" it; otherwise, the reference to this will be null. // Using bind from constructor is one way to do this, as in the following line. FetchData = this.fetchdata.bind (this); } componentDidMount() { this.fetchData(); } fetchData() {fetch(REQUEST_URL).then(responseData => response.json()).then(responseData => { SetState ({data: this.state.data.concat(responsedata.movies), loaded: true}); }); } render() { if (! this.state.loaded) { return this.renderLoadingView(); } return ( <FlatList data={this.state.data} renderItem={this.renderMovie} style={styles.list} /> ); } renderLoadingView() { return ( <View style={styles.container}> <Text>Loading movies... </Text> </View> ); } renderMovie({item}) {// {item} is a function of the FlatList. Return (<View style={styles.container}> <Image source={{uri: item.posters.thumbnail }} style={styles.thumbnail} /> <View style={styles.rightContainer}> <Text style={styles.title}>{item.title}</Text> <Text style={styles.year}>{item.year}</Text> </View> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, flexDirection: "row", justifyContent: "center", alignItems: "center", backgroundColor: "#F5FCFF" }, rightContainer: { flex: 1 }, title: { fontSize: 20, marginBottom: 8, textAlign: "center" }, year: { textAlign: "center" }, thumbnail: { width: 53, height: 81 }, list: { paddingTop: 20, backgroundColor: "#F5FCFF" } });Copy the code

This example takes the 25 most recently released movies from the movie database and displays them in a FlatList.

 

2.1 the import

import React,{Component} from 'react'; // Import a default Component for export from the 'react' file. Name it react and the non-default Component ComponentCopy the code

There are also other uses of import, with the following meanings:

    • Import defaultcomponent form ‘XXX’ imports the defaultcomponent in the XXX file named defaultcomponent
    • Import {a} from ‘XXX’ imports component A in the XXX file
    • Import {a as B} from ‘XXX’ imports component A in the XXX file and renames it to b
    • Import * as a from ‘XXX’ import all components in the XXX file, name it a, and invoke specific components as a.b, A.C… The default components are not included

 

2.2 var Defines variables

In front of the component, specify a variable REQUEST_URL to hold the request url.

 

2.3 the export statement

The function of a module has two keywords: export and import. Export is used for user-defined modules. Import is used to input functions of other modules and create namespaces to prevent function name conflicts.

ES6 allows separate JS files as modules, that is, allows one JavaScript script file to call another script file. The simplest module is a JS file that outputs variables using the export keyword.

//profile.js export var firstName = "Pandora"; export var lastName = "G.Dragon"; export var year = 1973; Var firstName = "Pandora"; var firstName = "Pandora"; var lastName = "G.Dragon"; var year = 1973; export({firstName, lastName, year});Copy the code

Once a module is defined using export, other JS files can load the module (file) using the import keyword. The loading mode is as follows:

    import {firstName, lastName, year} from './profile';
    function setHeader(element) {
        element.textContent = firstName + '' + lastName;
    }
Copy the code

In the code snippet above, the import keyword is used to accept an object — represented by “{}”. This specifies variables to import from other modules. The variable name inside the braces must be the same as the name of the external interface of the imported module.

 

2.4 Class Class

ES6 provides a more traditional language approach, introducing the concept of classes as templates for objects. With the class keyword, you can define a class. Basically, ES6 classes can be seen as a syntactic candy that does most of what ES5 does. The new class writing method simply makes object prototype writing clearer and more like object-oriented programming syntax. The above code is rewritten using ES6 “classes”, as follows.

Class Point {constructor(x, y) {this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; }}Copy the code

The above code defines a “class”. You can see that it contains a constructor method, which is the constructor, and the this keyword represents the instance object. That is, ES5’s Point constructor corresponds to ES6’s Point class constructor.

In addition to the constructor, the Point class defines a toString method. When you define a method of a class, you don’t need to use the function keyword; you can just use the function definition. In addition, methods do not need to be separated by commas, which will cause errors.

Classes can be inherited using the extends keyword, which is much cleaner and more convenient than ES5’s modified prototype chain.

class ColorPoint extends Point {}
Copy the code

The above code defines a ColorPoint class that inherits all the properties and methods of the Point class through the extends keyword. But since no code is deployed, the two classes are exactly the same, duplicating a Point class. Next, we add code inside ColorPoint.

class ColorPoint extends Point { constructor(x, y, color) { super(x, y); // Call the parent class constructor(x, y) this.color = color; } toString() { return this.color + ' ' + super.toString(); // Call toString()}}Copy the code

In the above code, the super keyword appears in both the constructor and toString methods, where it represents the parent’s constructor, which is used to create a new parent’s this object.

Subclasses must call the super method from the constructor method or they will get an error when creating a new instance. This is because the subclass does not have its own This object, but inherits the parent’s This object and then processes it. If you don’t call super, your subclasses don’t get this.

 

2.5 Props (Properties)

Most components can be customized at creation time with various parameters. These parameters for customization are called props (properties).

Take the common basic component Image as an example. When creating an Image, you can pass in a prop named Source to specify the address of the Image to display and use a prop named style to control its size.

import React, { Component } from 'react'; import { Image } from 'react-native'; export default class Bananas extends Component { render() { let pic = { uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' }; return ( <Image source={pic} style={{width: 193, height: 110}} /> ); }}Copy the code

 

2.6 the state

Props is specified in the parent component, and once specified, it does not change during the life of the specified component. For data that needs to change, we need to use state.

Most components can be customized at creation time with various parameters. These parameters for customization are called props (properties).

In general, you need to initialize state in constructor. This is how ES6 is written. Many early ES5 examples used the getInitialState method to initialize state, which will be phased out) and then called the setState method when changes are needed.

Here are some key points that beginners should keep in mind:

  • All interface changes are state state changes

  • State must be modified through the setState() method

    • this.state.likes = 100; / / thisDirect assignment changes are invalid!
    • SetState is a merge merge operation that only modifies specified attributes and does not affect other attributes
    • SetState isasynchronousOperation, modifyNot immediately

 

2.7 React Native Life cycle

The component lifecycle approach corresponds to the different life stages of the component, which are usually divided into three phases: the component initialization and mount phase, the component run-time phase, and the component unload phase.

  • Initialization and mount phases

This is the constructor of the component class, where the state data model is normally initialized.

constructor(props) {
  super(props);
  this.state = {
    //key : value
  };
}
Copy the code

The component will be loaded into the virtual DOM, executed before the Render method, and executed only once during the entire lifecycle.

componentWillMount() {
}
Copy the code

The component is loaded into the virtual DOM and executed after the Render method, only once during the entire lifecycle. This method is typically used to complete asynchronous network requests or integrate other JavaScript libraries.

componentDidMount() {
}
Copy the code
  • Run-time stage

Execute when the component receives props from the parent component, and the parameter is props from the parent component. It can be executed multiple times throughout the life of a component. Normally, this method receives the new props value and resets the state.

componentWillReceiveProps(nextProps) {
  this.setState({
    //key : value
  });
}
Copy the code

Second, in componentWillReceiveProps (nextProps) executed immediately; Or immediately after the state change. This method contains two parameters, props and state. This method can be executed multiple times throughout the life cycle of the component. If the method returns false, then componentWillUpdate(nextProps, nextState) and subsequent methods are not executed, and the component is not re-rendered.

shouldComponentUpdate(nextProps, nextState) {
  return true;
}
Copy the code

ShouldComponentUpdate (nextProps, nextState) shouldComponentUpdate(nextProps, nextState) shouldComponentUpdate(nextProps, nextState) Called before the render() function executes. This method can be executed multiple times throughout the life cycle of the component.

componentWillUpdate(nextProps, nextState) {

}
Copy the code

Call immediately after render() is executed. This method contains two parameters, props and state. This method can be executed multiple times throughout the life cycle of the component.

componentDidUpdate(preProps, preState) {

}
Copy the code

The render method is used to render components. It is executed in both the initialization and run-time phases.

render() {
  return(
    <View/>
  );
}
Copy the code
  • Unloading phase

Called when the component is unloaded by the virtual DOM.

componentWillUnmount() {
}
Copy the code

 

2.8 the fetch

Fetch, in plain English, is an alternative to XMLHttpRequest. If someone asks you, are there alternatives to Ajax for getting background data? The answer is that a better solution, FETCH, could also be used.

As of now, FETCH support is not very good, but it is supported in Google Chrome. Fetch hangs in the BOM and can be used directly in Google Chrome.

Check the fetch support status: The FETCH support status

The fetch method returns a Promise, which simplifies asynchronous style code. If you want to understand what promises mean, check out this article: A Step-by-step guide to Making a Full Promise. Take you to the heart of promise.

Let’s write the first fetch example to fetch back-end data:

/ / through the fetch access to baidu's error page fetch (' https://www.baidu.com/search/error.html ') / / return a Promise object. Then ((res) = > {return res. The text () // res.text() is a Promise object}).then((res)=>{console.log(res) // res is the final result})Copy the code

Isn’t that easy? Let’s look at the use of the GET and POST methods:

/ / through the fetch access to baidu's error page fetch (' https://www.baidu.com/search/error.html?a=1&b=2 '{/ / write parameters passed in the URL method: 'GET'}) / * post method, GET in front of the note can fetch (' https://www.baidu.com/search/error.html '{method: "post", the body: new URLSearchParams([["foo", 1],["bar", 2]]). The toString () / / here is the request object}) * /. Then ((res) = > {return res. The text ()}), then ((res) = > {the console. The log (res)})Copy the code

React Native has built in the XMLHttpRequest API (also known as Ajax). Some third-party libraries based on the XMLHttpRequest wrapper are also available, such as Frisbee or AXIos. But be careful not to use jQuery, because jQuery also uses a lot of things that are available in browsers that are not available in RN (so not all ajax libraries on the Web can be used directly).

 

2.9 style

Style is defined as:

  • Define it directly in the render () function
Var mStyle = {color:'red',fontSize:34}; Return < Text style = {mStyle} > https://github.com/93Laer < / Text > / / / is similar to the anonymous inner android / / return within < Text style={{color:'red',fontSize:34}}> https://github.com/93Laer </Text>Copy the code
  • 2. Method 2: Create style by StyleSheet, test multiple styles, whichever prevails
// Const styles = StyleSheet. Create ({bigblue:{color:'blue', fontSize:34, fontWeight:'bold'}, red:{color:'red', fontSize:14 } }); Return <Text style={styles.bigblue}> HTTPS ://github.com/93Laer </Text>Copy the code

Pass multiple style objects directly into the component, and the final effect is not displayed, but the conclusion is given at the end

Var mStyle = {color:'red',fontSize:34}; return<Text style={[mStyle,{color: 'blue',fontSize:20}]}> https ://github.com/93Laer </Text>Copy the code

Create multiple styles with StyleSheet and pass them in

 return<Text style={[styles.bigblue,styles.red]}> https ://github.com/93Laer </Text>
Copy the code
Conclusion: When setting multiple styles, use the last one to override the previous style. Style takes style out of the Styles array and assigns it to itself, so the last assignment will showCopy the code

This concludes the basics of React Native.