React

Complete code stamp git

React first 篇 NPM, yarn introduction react second 篇 NPM, yarn Introduction react react third 篇 Single page application development react third 篇 Route &Hooks react fifth 篇 Synthet application (login + list)

React Redux Redux Redux Redux


Mainstream front-end frameworks:

  • vue(mvvm)
  • react (mvvm)
  • angular(mvc)

1. Introduce the React

features

  • Declarative: For example, declare variables. React allows you to declare components and variables
  • componentization
    • Individual modules are developed into widgets that are nested on different pages, similar to stacking logs
    • Any big project can be broken down into countless small projects, and small projects can be broken down into small components
    • Put the blocks together and stack them into a large project
    • The difference between modularity and componentization: == Modularity focuses on UI== as opposed to functionality (e.g., payment, order made into separate functions)
  • flexible
    • Supports single page and multiple pages, and distributes different pages through routing
    • Support server rendering, throw React into Node.js and render multiple pages
    • React Native App development

Introducing way

cdn

  • unpkg.com/react@16/um…
  • unpkg.com/react-dom@1…
  • Unpkg.com/babel-stand…

The basic grammar

  • Reactdom.render () renders elements such as div
  • The React core library provides various apis for manipulating the DOM
  • React.componentes6 syntax, often inherited from React.componentby extents in development

2. Write Hello World

  • First, vi command touch index.html to create the program entry
  • Introduce react in CDN or NPM mode
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>React demo 4</title> <! -- CDN --> <script SRC ="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <! Babel --> <script SRC ="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <! -- or NPM --> <! -- <script src="./node_modules/react/umd/react.development.js"></script>
    <script src="./node_modules/react-dom/umd/react-dom.development.js"></script> -->
</head>
<body>
    <div id = "app"></div>
    <script>
        var hello = React.createElement('h1', {},"Hello world!");
        ReactDOM.render(hello,document.getElementById('app'));
    </script>
</body>
</html>
Copy the code
  • ES6 syntactic sugar
    • Insert Babel and add type=”text/ Babel “to div script to write HTML tags directly under script
    <head> ... <! Babel --> <script SRC ="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 
      ...
    </head> 
     
     ...
     
    <body>
        <div id = "app"></div>
        <script type = "text/babel">
            // var hello = React.createElement('h1', {},"Hello world!");
            // ReactDOM.render(hello,document.getElementById('app'));
            ReactDOM.render(
                <h1>Hello,World</h1>,
            document.getElementById('app'));
        </script>
    </body>
    
    Copy the code

3. The JSX is introduced

  • 1 is to write HTML code in JS
// var hello = react. createElement('h1',
    // {
    //     className:'red',
    //     name:'jack'/ / / /}"Hello world!");
    // ReactDOM.render(hello,document.getElementById('app')); // reactdom.render (<h1 className="red" name="jack">Hello,React</h1>,
    document.getElementById('app'));
Copy the code
  • 2 At the same time, HTML can also be nested JS code
// 2 Insert js code var name ='jack';
    var ele = <h1 className="red" name="jack">Hello,{name}</h1>;
    ReactDOM.render(
        ele,
    document.getElementById('app'));
Copy the code

4. Element rendering

  • React updates only what is necessary
  • Note that the React DOM first compares the sequence of elements and only updates the changed parts during rendering.
  • Modify the code and re-render every 1s, check the Chrome console
// Render the elementfunction tick(params) {
            var time = new Date().toLocaleTimeString();
            var ele = <div>
                    <h1 className="red" name="jack">Hello,jack</h1> <h2> Now is, {time} </h2> </div> reactdom.render (ele, document.getelementbyid ('app'));
        }
        setInterval(() => {
            tick();
        }, 1000);   
Copy the code
  • As you can see, only the changed node is re-rendered, not the entire tag
  • Vue is bidirectional and React is unidirectional

Components and Props

Common UI, such as header components, bottom components, breadcrumbs, etc. are used by multiple pages, so it needs to be made into a component that can be changed at a time to improve development efficiency

Create a way

  • Functional components (stateless components, no life cycle)
    • Property is obtained by props. Name
  • Inherited from React.Com Ponent (stateful component, with life cycle)
    • Stateful component, property obtained by this.props. Name
//5 components and props //5.1 Functional Components, stateless //function Hello(props) {
        //     returnThe < div > / / < h1 > Hello, {props. The name} < / h1 > / / < p > age: {props. Age} < / p > / / < p > good at: Everything</p> // </div> // } // ReactDOM.render( // <Hello name ="jack" age = "29"/>,
        //         document.getElementById('app')); Class HelloJack extends React.Component{render() {returnThe < div > < h1 > Hello, {this. Props. The name} < / h1 > < p > age: {this. Props. Age} < / p > < p > good at: Everything</p> </div> } } ReactDOM.render( <HelloJack name ="jack" age = "29"/>,
                document.getElementById('app'));
    
Copy the code

React Lifecycle

Four stages

  • 1) Component initialization phase
    • Property initialization
    • State initialization
  • 2) Component loading stage
    • Get property values
  • 3) Data update stage
    • The component property value has changed
  • 4) Component destruction stage

Class HelloJack extends React.Component{// Constructor can be excused {console.log(){// React lifecycle class HelloJack extends React.Component{// constructor can be excused {console.log()'Initialization phase'// Initialize props super(props); // Initialize state this.state = {name:'jack',
                    age:25
                }
            }

            componentWillMount(){
                console.log('Component before loading'// Can make ajax requests, request data manipulation}componentDidMount(){
                console.log('Component after loading')} updateUser =()=>{// error syntax //this.state.name ='Time';
                this.setState({
                    name:'Tim',
                    age:32
                })
            } 

            shouldComponentUpdate(){// General defaulttrue// Based on specific service scenarios, you can add criteria, such as updating the console. Log ('Does the data need to be updated')
                return true;
            }

            componentWillUpdate(){
                console.log('Data will be updated')}componentDidUpdate(){
                console.log('Data has been updated')}renderRender console.log(){render console.log(){render console.log()'Component load or data update')
                returnThe < div > < h1 > Hello, {this. State. The name} < / h1 > < p > age: {this. State. The age} < / p > < p > good at: Everything</p> {/* Bind updateUser without parentheses, <button onClick={this.updateUser}> </button> </div>}} reactdom.render (<HelloJack />, document.getElementById('app'));
Copy the code

7. Event handling

Event names are humped in four ways, such as onClick:

  • Method 1: The arrow function is dynamically bound as updateUser(){… }, undefined
  • Mode 2: Bind the updateUser2 object during initialization (set pointer)
  • The arrow function in onClick directly binds the function
  • OnClick this.updateUser3.bind(this)
Class HelloJack extends React.Component{// Constructor (){// Initialize props super(props); // Initialize state this.state = {name:'jack', age:25 } this.updateUser2 = this.updateUser2.bind(this); } // Mode 1 arrow function dynamic binding if writtenupdateUser(){...},就会undefined
            updateUser =()=>{
                console.log(this);
                this.setState({
                    name:'Tim', age:32})} // Bind the updateUser2 object during initialization, (set pointer)updateUser2(){
                console.log(this);
                this.setState({
                    name:'Joy'Bind (this.updateUser3.bind(this.updateUser3.bind(this));updateUser3(){
                console.log(this);
                this.setState({
                    name:'Stephen',
                    age:30
                })
            }

            render() {returnThe < div > < h1 > Hello, {this. State. The name} < / h1 > < p > age: {this. State. The age} < / p > < p > good at: Everything</p> <button onClick={this.updateUser}> </button><br/> <button OnClick ={this.updateUser2}> update data 2</button><br/> <button onClick={()=>this.updateUser3()}> </button><br/> <button </button> </div>}} reactdom.render (<HelloJack />, document.getelementById ())'app'));
Copy the code

8. Conditional processing

8.1 If else and Ternary Expressions

//8. Conditional processingfunction Login() {return<button > login </button>}function LogOut() {return</button>} class App extends React.Component{state = {isLogin:false
            }

            updateUser =()=>{
                console.log(this);
                this.setState({
                    isLogin:true})}render(){// Get state const isLogin = this.state.islogin; // const{isLogin} = this.state; //1.ifelse
                // letele; / / for declarationletIf it is const, the value cannot be changedif (isLogin) {
                //     ele = <Login/>
                // }else{
                //     ele = <LogOut/>
                // }

                return<div> <h1>Hello,{this.state.name}</h1> {/*{ele}*/} {/* 2. */} {isLogin? <Login/>:<LogOut/>} <br/> <button onClick={this.updateUser}> </button><br/> </div>}} reactdom.render (<App />, document.getElementById('app'));
Copy the code

8.2 Method by which a child component triggers a parent component

        functionLogin(props){// The child component receives the updateUser method via the props propertyreturn<button onClick={props. UpdateUser}> </button>}function LogOut(props){
            return<button onClick={props. UpdateUser}> </button>} class App extends React.Component{state ={isLogin:false} updateUser =()=>{ console.log(this); this.setState({ isLogin:! this.state.isLogin }) }render(){
                const isLogin = this.state.isLogin;
                
                return<div> <h1>Hello,{this.state.name}</h1> {/* Pass the updateUser method to the child component */} {isLogin?<Login updateUser={this.updateuser}/> :<LogOut updateUser={this.updateUser}/>} <br/> </div> } } ReactDOM.render( <App />, document.getElementById('app'));
Copy the code

9. List rendering

State = {List :[1,2,3,4,5], list2:[{id:1,text:'java'},
                    {id:2,text:'js'},
                    {id:3,text:'php'},
                    {id:4,text:'python'},
                    {id:5,text:'node'}}]render(){ const arr = this.state.list; const arr2 = this.state.list2; Const listItem = [] const listItem2 = [] const listItem2 = []letli = <li>{item}</li>; listItem.push(li); / / or})forCycle / /for (let i = 0; i < arr.length; i++) {
                //     let li = <li>{arr[i]}</li>;
                //     listItem.push(li);
                // }
                for (let i = 0; i < arr2.length; i++) {
                    let li = <li key={arr2[i].id}>{arr2[i].text}</li>;
                    listItem2.push(li);
                }
                return <div>
                        <ul>
                            {listItem}
                            {listItem2}
                        </ul>
                    </div>
            }
        }
        ReactDOM.render(
                    <List />,
                document.getElementById('app'));
Copy the code

10. Forms applications

Class ToDoList extends React.Component{state = {value:' ', list:[] } handleAdd = ()=>{ const val = this.state.value; const list = this.state.list; // const{val,list} = this.state; list.push(val); This.setstate ({list:list //es6 when list and value are equal, HandleInput = (event)=>{this.setState({value:event.target.value})} handleInput = (event)=>{this.setState({value:event.target.value})}render(){
                const val = this.state.value;
                const arr = this.state.list;
                const listItem = []
                arr.map((item,index)=>{
                    let li = <li key = {index}>{item}</li>;
                    listItem.push(li);
                })

                return <div>
                        <div>
                            <input type = "text"Value ={val} onChange={this.handleInput}/> <button onClick={this.handleAdd}> Add entry </button> </div> <ul> {listItem} </ul> </div> } } ReactDOM.render( <ToDoList />, document.getElementById('app'));
Copy the code