2020-9-14, react framework entry, scaffold, component and event binding

Content: introduction to react framework, scaffolding, components, event binding
Date: September 14, 2020

1, Introduction to react framework

1. Introduction

react is an Open-Source Library of facebook and a JavaScript library for building user interfaces. It is not a complete MVC. It can be considered as the V (view layer) in MVC at most.

Official website: https://react.docschina.org/

Advantages:

Good browser compatibility

Everything is a component

Virtual DOM (diff)

JSX syntax sugar

Disadvantages:

It is not a complete MVC design pattern. It cannot develop large-scale projects by itself. It needs to combine flux and redux.

2. Basic use

Step 1: introduce core library

<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

Step 2: set up a container

<div id="app"></div>

Step 3: create a virtual DOM and render it to the page

ReactDOM.render(React.createElement('h1',{},"This is a h1 title"),document.getElementById('app'))

3.JSX syntax [optional, recommended]

Using the createElement method can create a virtual DOM, but if the structure and hierarchy of the virtual DOM are complex, it will be very difficult to use the createElement method. Therefore, facebook has developed a set of JSX syntax sugar specifically for React.

JSX syntax candy is a set of syntax candy specially developed by facebook for react. It is not a new grammar, but integrates the previous js and html to facilitate program developers to better develop and read code.

JSX allows JavaScript and HTML to be mixed together.

Features: it will be parsed into HTML syntax when encountering < and JS syntax when encountering {.

Step 1: introduce the core library for parsing JSX syntax

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Step 2: modify the type attribute of script

<script type="text/babel">

The type attribute of script is text/javascript by default, and the browser will recognize that the script code written in the script is js

Step 3: create a virtual DOM and render it to the page

var el = <div>
    <p>jsx Use of grammar sugar</p>  
    <span></span>
</div>
ReactDOM.render(el,document.getElementById('app'))

4. Data type analysis

<script type="text/babel">
    // character string
    var str = 'hello react';
    // number
    var num = 145
    // Boolean value in react, Boolean value cannot be directly rendered, and condition judgment can be carried out
    var islogin = false;
    // Object in react, the object type data cannot be directly rendered, but an attribute in the object can be rendered
    var obj = {
        name:'Xiaofei',
        age:20
    }
    // Array in react, if the array element is an object, it cannot render the object to the page
    var arr = [{title:'title',price:200}]
    var el = (
        <div>
        <h1>{ str }</h1>
        <p>{ 'number:' + (num+10) }</p>
    <p>{ islogin ? 'Logged in' : 'Not logged in' }</p>
    <p>{ obj.name }</p>
    <p>{ arr }</p>
    </div>
    );
    var box = document.getElementById('box')
    ReactDOM.render(el,box);
</script>

5. Attribute binding

className

style

<li className="red" key={index} style={{ fontSize:26 }}

In style

The first curly bracket resolves into js syntax, and the second curly bracket represents an object

The pixel unit is px by default, so you don't need to write. If it's other units, it needs to be spliced

img

var imgurl = 'Picture address'
<img src={ imgurl } />

2, Common errors

1.babel.min.js:7 Uncaught SyntaxError: Inline Babel script: Adjacent JSX elements must be wrapped in an enclosing tag (5:57)

Virtual DOM can only have one root tag

2.Warning: Invalid DOM property class. Did you mean className?
in div

In react, class is the keyword of the class, so the class attribute cannot be used, but the className should be used

3.Uncaught SyntaxError: Inline Babel script: Unterminated JSX contents

In jsx, all tags must have closure, including single closure tags

input,img,br,hr

4.Warning: Invalid DOM property for. Did you mean htmlFor?

In react, for is the keyword to traverse the loop. The label tag cannot use the for attribute and needs to be changed to htmlFor

5.Warning: Each child in a list should have a unique "key" prop.

When traversing the loop to generate virtual DOM, you need to set a key attribute to the virtual DOM to uniquely identify the DOM structure and speed up rendering.

6.react-dom.development.js:6824 Uncaught Error: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.

In the jsx syntax of react, style expects an object, not a string

7.Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

The component name of react should be capitalized

3, Scaffolding

1. Installation

npm i create-react-app -g

2. Initialize project

Enter a specified directory (not recommended on the desktop)

create-react-app entry name

3. Operation project

Enter the project root directory and execute the command

npm start

4. Project directory structure

entry name

​ node_modules project dependency directory

public project running root directory

​ index.html project running home page

src project source directory

​ index.js project startup file

​ index.css project global style file

​ App.js project root component

​ App.css project root component style

5. Project operation process

/public/index.html

/src/index.js

/src/App.js

4, Components

1. Functional components

It does not have its own business logic, stateless components (puppet components)

(1)es5 mode

var Home = function(){
    return(
        <div>
            <h1>home page</h1>
        </div>
    )
}
export default Home;

(2)es6

export default ()=>{
    return(
        <div>
            <h1>home page</h1>
        </div>
    )
}

2. Class components

State component (business component), and class component has a life cycle.

Example code:

Mode 1:

import React from 'react'
class Order extends React.Component{
    constructor(){
        super();
        console.log('Constructor executes first')
        // console.log(this)
    }
    render(){
        console.log('render Function executed')
        return(
            <div>
                <h1>This is order page</h1>
            </div>
        )
    }
}
export default Order;

Mode 2:

import React,{ Component } from 'react'
export default class Order extends Component{
    render(){
        return(
            <div>
                <h1>This is order page</h1>
            </div>
        )
    }
}

5, Events

1. Event binding

(1)es5 mode

When binding a click event to a button, do not write parentheses when you do not need to pass parameters, otherwise the specified function will be executed automatically.

import React,{ Component } from 'react'
export default class Index extends Component{
    render(){
        return(
            <div>
                <h1>index page-event</h1>
                {/* Event binding -es5 mode */}
                <button onClick={ this.addnum }>click</button>
            </div>
        )
    }
    addnum(){
        console.log('addnum....')
        console.log(this)
    }
}

At this time, this cannot be obtained in the bound function. If you want to obtain this in the custom function, bind is required

<button onClick={ this.addnum.bind(this) }>click-es5-have this</button>

(2)es6 mode

<button onClick={ ()=>this.handler1() }>click-es6</button>

Arrow function to keep this pointing

2. Event object

(1)es5 mode

<button onClick={ this.handler2 }>Event object-es5</button>

In es5 mode, when an event triggers a function, no parameters are passed. If there is a formal parameter in the corresponding event function, this formal parameter is the event object.

(2)es6 mode

<button onClick={ (e)=>this.handler2(e) }>Event object-es6</button>

In es6 syntax, if the event object is not actively passed, the event object cannot be obtained in the user-defined function.

3. Communication

(1)es5 mode

In es5 mode, when additional parameters need to be passed, bind(this, argument 1) should be used

The first formal parameter in the function definition is the passed argument, (the formal parameter is no longer an event object)

If you also want to get the event object, you need to add one more formal parameter (the last one) in the function definition, which is the event object

<button onClick={ this.handler3.bind(this,'hello',100) }>Transfer parameters-es5</button>

js code

handler3(e,str,ev){
    console.log(e,111111)
    console.log(str,22222)//The first two parameters are passed arguments
    console.log(ev)//ev is the event object
    // console.log(this)
}

(2)es6 mode

<button onClick={ (e)=>this.handler3(e,'test',555) }>Transfer parameters-es6</button>

When es6 uses the arrow function to call a custom function, what is passed by the argument and what is received by the formal parameter.

6, State machine

Each class component has a state attribute. We can put the initial data of the page component into the state.

When you need to modify the initial data in the page and re render the page, you need to use the setState function

setState does two things:

The first is to merge the specified data with the data in the original state

The second is to call diff algorithm to re render the page.

import React, { Component } from 'react'
export default class Order extends Component {
    constructor(){
        super();
        this.state = { num:100 }
    }
    add(){
        // this.state.num++;
        // this.render();// This method will modify the data, but the page will not change
        var num = this.state.num;//state cannot be modified directly in react, so take out the original value first and then modify it
        this.setState({
            num:++num
        })
    }
    render() {
        console.log('The page is rendered....')
        return (
            <div>
                <h1>order page</h1>
                <p>The order quantity is:{ this.state.num }</p>
                <button onClick={ ()=>this.add() }>Click Add</button>
            </div>
        )
    }
}

7, Simulate bidirectional binding of form elements

import React, { Component } from 'react'

export default class Form extends Component {
    state = {
        username:'',
        phone:''
    }
    iptChange(e){
        // console.log(e.target)
        // this.setState({
        //     username:e.target.value
        // })
        var data = this.state;
        data[e.target.id] = e.target.value;
        this.setState(data)
    }
    submit(){
        console.log(this.state)
    }
    render() {
        return (
            <div>
                <h1>Form information collection</h1>
                user name:<input type="text" id="username" value={ this.state.username } onChange={ (e)=>this.iptChange(e) }/>
                <p>{ this.state.username }</p>
                <br/>
                cell-phone number:<input type="text" id="phone" value={ this.state.phone } onChange={ (e)=>this.iptChange(e)}/>
                <p>{ this.state.phone }</p>
                <br/>
                <button onClick={ ()=>this.submit() }>Submit</button>
            </div>
        )
    }
}

Tags: Vue

Posted by amalosoul on Tue, 17 May 2022 16:30:47 +0300