This is the second day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Introduction to React:
React came out of Facebook’s open source project
React can develop a single page app SPA
React component modular development mode
React minimizes interactions with the DOM (data binding) by simulating the DOM (virtual DOM)
React is flexible. React works well with known libraries or frameworks.
React is based on JSX syntax. JSX is the core component of React. It uses XML markup to directly declare the interface, HTML AND JS mixing mode
Preparation before setting up the React development environment.
Note: Install the stable version of NodeJS
Install CNPM. Replace NPM with CNPM
Address: npm.taobao.org/
Install CNPM:
npm install -g cnpm –registry=registry.npm.taobao.org
3. Use YARN to replace NPM
Yarn installation:
The first method: refer to the official yarn.bootcss.com/
Method 2: CNPM install -g yarn or NPM install -g yarn
Build the React development environment
The first method (old – now recommended) :
Reactjs.org/docs/create…
Note: Install the stable nodeJS version. Nodejs version: V8.11.2 NPM version: V5.6.0
2. Install the scaffolding tool (single file component project generation tool) only once
npm install -g create-react-app / cnpm install -g create-react-app
3. Create the project (possibly multiple times)
Find the directory where the project will be created:
create-react-app reactdemo
4. CD into the project
cd reactdemo
NPM start yarn start Running the project
NPM run build yarn build Generates a project
Second approach (new – Future recommendation) :
Reactjs.org/docs/create…
Note: Install the stable nodeJS version. Nodejs version: V8.11.2 NPM version: V5.6.0
2. Install scaffolding tools and create the project
Find the directory to create the project to execute:
npx create-react-app reactdemo
4. CD into the project
cd reactdemo
NPM start Run the project (debug)
NPM Run Build
NPX is introduced:
A command (NPX) introduced in NPM v5.2.0 to improve the experience of using the command-line tools provided in the package.
Details:
www.phonegap100.com/thread-4910…
NPX create-react-app reactDemo this command will temporarily install the create-react-app package. The next time you execute it, it will be temporarily installed again.
NPX will help you execute the binaries in the dependency package.
For example, NPX http-server can help you start a static server in one sentence
A brief introduction to manifest.json file:
Lavas.baidu.com/mip/doc/eng…
One of the key features of the PWA is the ability to add sites to the home screen. The manifest.json standard is still in draft form. Chrome and Firefox already implement this feature, Microsoft is working on Edge, and Apple is still considering it
Super keyword:
Reference: www.phonegap100.com/thread-4911…
Es6 super can be used in class inheritance, the super keyword, which refers to an instance of the parent class (that is, the parent’s this object). Subclasses must call the super method within the constructor method, otherwise an error will be reported when creating an instance. This is because a subclass does not have its own this object, but inherits from its parent class’s this object and then processes it. If the super method is not called, the subclass will not get this object. class Person { constructor (name) { this.name = name; } } class Student extends Person { constructor (name, age) { super(); // In constructors, this. Age = age must be called before this is used; }, props (props) :
There is only one reason to pass props as an argument to super(), and that is if you need to use this.props inside the constructor
It’s all right to write super(props). It’s all right to write super(props).
ReactJSX grammar
JSX is a combination of Javascript and XML. React invented JSX, which makes it easy to create a virtual DOM using HTML syntax. When it comes to <, JSX parses it as HTML and when it comes to {, it parses it as JavaScript.
1, all of the template is a root node contains to return back in the render function can contain only a top-level label, otherwise it will be an error
2. Do not quote template elements
3, JSX basic syntax rules, encounter HTML tags (beginning with <), with HTML rules parsing; When a block of code (beginning with {) is encountered, it is resolved using the JS rules
4. Note of binding properties:
Class is going to be className
For is going to be htmlFor
The style property is written a little differently than before
<div style={{‘color’:’blue’}}>{this.state.title}
<div style={{‘color’:this.state.color}}>{this.state.title}
5, loop data to add key
6. Be sure to pay attention to super in component constructors
Subclasses must call the super method within the constructor method, otherwise an error will be reported when creating an instance. This is because a subclass does not have its own this object, but inherits from its parent class’s this object and then processes it. Constructor (props){2 super(props); This. State ={4 userinfo:’ 3 ‘5} 6} 7
8, react parse HTML
1 <div dangerouslySetInnerHTML={{__html: this.state.list.htmlStr}}> </div>
Copy the code
9. Four ways to write conditional judgment
Using ternary expressions, using DOM element variables, calling functions directly, using logical operators, \ 1 class HelloWorld extends React.Com {2 render(){3 return
Hello {4 (function(obj){5 if(obj.props.name){ 6 return obj.props.name; 7 }else{ 8 return “World”; 9 } 10 }(this)) 11 }
12 } 13 }
Fragments label
With the outermost DIV, the component is perfectly fine, but what if your layout doesn’t need that outermost tag? For example, when we do Flex layouts, we really can’t have wrapping elements on the outside. React16 takes this contradiction into account by giving us the
tag.
In a component defined as class inheritance, it is usually necessary to point this at the runtime of the event handler to the current component instance in order to easily call other member methods or properties of the current component (such as this.state).
Introduction method:
import React,{Component,Fragment } from 'react'
Copy the code
Then replace the outermost
tag
setState
React does not allow direct manipulation of state, and while the above method works, it can be cumbersome to optimize late performance
There are several ways to bind the event handler this:
The first method:
4 <button onClick={this.run.bind(this)}> </button>Copy the code
The second method: change in the constructor
1 this.run = this.run.bind(this); 2 run(){3 alert(this.state.name) 4} 5 <button onClick={this.run> </button>Copy the code
The third way:
1 <button onClick={this.run> </button> 2 <button onClick={this.run>Copy the code
Components in React: Address the shortcomings of HTML tag building applications.
Gets the value of the form
(Get the key value e.keycode for a key clicked)
1, listen for the form change event onChange
2, in the changed event to get the form input value ref get
Username this.setstate ({});
Select username this.state.username from “state” when clicking the button
Component pass values:
The benefit of using components is that common functions are separated into a file as a component and imported where they are used.
Parent and child components: When components call each other, the caller is called the parent component and the caller is called the child component
Parent and child components pass values:
One, the parent component passes values to the child component
1. Define a property when the child component is called
This.props. MSG: this.props
Note: The parent component can not only pass values to the child component, but also can pass methods to the child component, and the entire parent component to the child component.
Remember that a parent component passes content to a child component in the form of properties.
The parent component actively obtains data from the child component
1. Specify the value of ref when calling the child component
2. Get the entire subcomponent instance via this.refs.header
2, the child component passes a value to the parent component:
DefaultProps: If the parent component does not pass a value to the child component when calling the child component, the child component can use the default value defined by defaultProps
PropTypes: Validates the type of values passed by the parent component and defines the type of values passed by the parent component to the child component
1. Import PropTypes from ‘prop-types’;
2, class.proptypes = {
name: PropTypes.string
};
Are defined in child components
Binding and non-binding components:
Non-binding groups: This defaultValue is actually the value attribute in the native DOM.
The value of this component is what the user typed. React does not manage the input process at all.
Binding components:
Here, the value property is no longer a write-down value, it is this.state.username, which is managed by this.handlechange.
In fact, the value of the input is not what the user entered at all. Instead, after the onChange event is triggered, this. SetState causes a re-render. React, however, will optimize the rendering process. It looks a bit like double break data binding
React gets data from the server APi:
React does not provide a specific module for requesting data. However, we can implement the request data using any third party request data module
1, axios github.com/axios/axios… The Authors at Axios find JSONP less friendly and recommend CORS as a cleaner approach (the back end runs across domains)
NPM install axios –save/NPM install Axios –save
Import axios from ‘axios’
Var API =”; axios.get(api) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 2, the fetch – the json github.com/camsong/fet…
NPM install fetch-jsonp –save
2, import fetchJsonp from ‘fetch-jsonp’
FetchJsonp (‘/users.jsonp’).then(function(response) {return response.json()}).then(function(response) {return response.json()}).then(function(response) { }). Catch (function(ex) {console. Log (‘parsing failed’, ex)}). You can also use native JS to implement data requests.
React lifecycle function:
Before the component is loaded, the component is loaded, and the component updates data, the component is destroyed.
This is the lifecycle function of the component
Function that fires when a component is loaded:
Constructor componentWillMount, render, componentDidMount
A lifecycle function that is triggered when component data is updated:
ShouldComponentUpdate, componentWillUpdate, Render, componentDidUpdate
This is triggered when you change the props pass value in the parent component:
componentWillReceiveProps
Triggered when a component is destroyed:
componentWillUnmount
Life cycle functions to remember:
* componentWillMount, render, componentDidMount (DOM)
When updating: componentWillUpdate, Render, componentDidUpdate
* Destruct when: componentWillUnmount
React route configuration:
1, find the official document reacttraining.com/react-route…
CNPM install React-router-dom –save
3, find the root component of the project and introduce react-router-dom
import { BrowserRouter as Router, Route, Link } from “react-router-dom”;
4. Copy the content in the root component of the official website document for modification (the loaded component should be introduced in advance)
< the Router > < Link to = "/" > home page < / Link > < Link to = "/ news" > news < / Link > < Link to = "/ product" > products < / Link > < the Route exact path = "/" component={Home} /> <Route path="/news" component={News} /> <Route path="/product" component={Product} /> </Router>Copy the code
Exact indicates strict matching
Realize JS jump route: reacttraining.com/react-route…
1. Introduce Redirect
2. Define a flag
this.state = {
loginFlag:false
};
3, judge the flag in render to decide whether to jump
if(this.state.loginFlag){
return <Redirect to={{ pathname: “/” }} />;
}
4, to perform js jump
Change the state of loginFlag using JS
After the change, the new render can Redirect itself to jump
CNPM install url –save when using url module in React
import url from ‘url’;
// Get the get pass value
console.log(url.parse(this.props.location.search,true));
var query=url.parse(this.props.location.search,true).query;
console.log(query)