Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

React Background

  • React Example tutorial

React grew out of an internal project at Facebook, where the company was unhappy with all the JavaScript MVC frameworks on the market and decided to write one for Instagram. After it was built, it was found to be very useful and opened source in May 2013.

What is the React

  • A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES

    • A JavaScript library for building the UI
    • React is not an MVC framework, just a library for the view (V) layer
  • The React website

  • React 英 文 版

The characteristics of

  • Use JSX syntax to create components and realize component-based development, which opens the door for functional UI programming
  • 2 high performance people praise: passThe diff algorithm 和 Virtual DOMEfficient update of views
  • HTML is just the beginning
> JSX --TO > everything-jsx --> htML-jSX --> Native Components in ios or Android (XML) -- JSX --> VR-jSX --> Internet of ThingsCopy the code

React basic use

  • Installation:npm i -S react react-dom
  • reactReact is the react library entry point
  • react-dom: provides methods for DOM, such as rendering the created virtual DOM to a page
// 1. Import react import react from 'react' import ReactDOM from 'react' Create virtual DOM // Parameter 1: element name parameter 2: element attribute object (null indicates none) Parameter 3: The current element's child elements string | | createElement method () the return value of a const divVD = React. The createElement method (' div '{title:' hello React}, 'hello, React!!! Render (divVD, document.getelementById ('app')); render(divVD, document.getelementById ('app'));Copy the code

The createElement method ()

  • Description:createElement()Way, code is not friendly, too complex
var dv = React.createElement( "div", { className: "shopping-list" }, React.createElement( "h1", null, "Shopping List for " ), React.createElement( "ul", null, React.createElement( "li", null, "Instagram" ), React.createElement( "li", null, // render reactdom.render (dv, document.getelementById ('app'))Copy the code

Basic use of JSX

  • Note: JSX syntax, which will eventually be compiled as the createElement() method
  • Recommendation: Use JSX to create components
  • JSX – JavaScript XML
  • Installation:npm i -D babel-preset-react(Dependent on: babel-core/babel-loader)

Note: JSX syntax needs to be compiled with babel-preset-react before it can be parsed

{"env" : ["env", "react"]} /* 2 webpack.config.js */ module: [rules: [ { test: /.js$/, use: 'babel-loader', exclude: /node_modules/},]] /* 3 Use JSX */ const dv = (<div title=" title "className=" CLS container">Hello JSX! </div>) /* 4 Render JSX to the page */ reactdom.render (dv, document.getelementbyid ('app'))Copy the code

The React components

The React component lets you break up the UI into separate, reusable pieces and treat each piece as independent of the other.

  • Components are made up of individual HTML elements
  • Conceptually, components are like functions in JS. They accept user input (props), andreturnReact object that describes what is displayed on the page

React creates components in two ways

  • 1 Create (stateless component) from JS functions
  • 2 Create (stateful components) by class
Use scenarios of functional components and class components: 1 If a component is only for displaying data, then it can use functional components. 2 If a component has some business logic and needs to manipulate data, then it needs to use class to create components, because, then, it needs to use stateCopy the code

JavaScript function creation

  • Note: 1 Function names must start with a capital letter. React uses this feature to determine if it is a component
  • Note: the 2 function must have a return value, which can be a JSX object ornull
  • Note: 3 return JSX, must haveaThe root element
  • Note: the return value of 4 components is used(a)Wrap to avoid line breaking problems
Function Welcome(props) {return (div className="shopping-list"> {/* <h1> shopping-list */} <h1> shopping-list  for {props.name}</h1> <ul> <li>Instagram</li> <li>WhatsApp</li> </ul> </div> ) } ReactDOM.render( <Welcome name="jack" />, document.getElementById('app') )Copy the code

The class to create

In ES6, a class is just a syntactic sugar, not a real class, essentially a constructor + stereotype implementation inheritance

// - ** All ES6 code runs in strict mode ** // -1 is used to define classes, // use the 'static' keyword to define static attributes // use the 'constructor' constructor. Create an instance attributes / / - / reference (http://es6.ruanyifeng.com/#docs/class) / / grammar: Class Person {// instance constructor(){// instance attribute this.age = age SayHello () {console.log(' hello, I am + this.age + '); } // Static method calls person.doudou () static doudou() {console.log(' I am Ming, I have a new skill, can warm the bed '); Person. StaticName = 'staticName' const p = new Person(19) class American extends Person { Constructor () {// Super () must be called, Super () this.skin = 'white' this.eyecolor = 'white'}} Based on the class in 'ES6', you need to work with 'Babel' to convert code to browser-aware ES5 syntax // install: 'NPM I -d babel-preset-env' // React object class ShoppingList extends React.Component {constructor() {super(props)} // class must create components that have rander methods and display a react object or null render() {return (<div) className="shopping-list"> <h1>Shopping List for {this.props.name}</h1> <ul> <li>Instagram</li> <li>WhatsApp</li> </ul> </div> ) } }Copy the code

Pass data to component – Parent component passes data

  • Component has oneRead-only objectcalledpropsUnable to add an attribute to props
  • How to obtain: function parametersprops
  • Effect: Converts a property passed to a component topropsProperties in objects
function Welcome(props){ // props ---> { username: 'zs', age: 20} return (<div> <div>Welcome React</div> <h3> name: {props. Username}---- age is: {props. Age}</h3> </div>)} // Pass props to Hello component: Reactdom.reander (<Hello username="zs" age={20}></Hello>,......)Copy the code

Encapsulate components into separate files

JSX creates the hello2.js component file. // 1. Introduce the React module. import React from 'react' // 2. Function Hello2(props){return (<div> <div> <h1> this is Hello2 component </div> <h1> </h1> <h6> This is a small H6 tag, I am small, I am proud!! Import Hello2 from './components/Hello2' </h6> </div>)}Copy the code

Props and state

props

  • Function: Passes data to a component, usually between parent and child components

  • React converts a property passed to the component into an object and gives it to props

  • Features: Props is read-only, and attributes cannot be added or modified to props

  • Props. Children: Gets the contents of a component, such as:

    • <Hello> Component contents </Hello>In theThe component content
// props is an object parameter that contains data. Do not attempt to modify the props parameter return value: Function Welcome(props) {// There must be only one root element in the react element. {props.name}</div> } class Welcome extends React.Component { constructor(props) { super(props) } render() { return <h1>Hello, {this.props.name}</h1> } }Copy the code

state

State as data

  • Function: Provides data to a component for internal use

  • Note: Only components created by class have state

  • Note: State is private and completely controlled by the component

  • Note: Do not add data to state that is not needed in the render() method, which will affect render performance!

    • You can add content to this that is used internally but not rendered in the view
  • Note: Do not call setState() in the Render () method to change the value of state

    • But you can get throughthis.state.name = 'rose'Mode set state (not recommended!!!!)
/ / case: Class Hello extends React.Com ponent {constructor () {/ / es6 inheritance must use super calls the superclass constructor super (). This state = {gender: 'male'}} render() {return (<div> gender: {this.state-gender}</div>)}}Copy the code