Where to start learning the basics of React?


Preface

English official website
Chinese official website

I compiled the react documents myself, combined with the official website and a summary of the knowledge I have learned. I hope it will be useful to you. Without further ado, read below:


1. Introduction to React

1. What is React?

**React**: JavaScript library for building user interfaces

2. The biggest difference between react and vue is:

On the surface, the syntax of templates is different, React renders templates through JSX. . Vue renders through an extended HTML syntax, but in fact this is just a superficial phenomenon. After all, React does not have to rely on JSX. . Deeply, the principles of templates are different, and this is their essential difference: React implements common syntax in templates through native JS in the component JS code, such as interpolation, conditions, loops, etc., all of which are implemented through JS syntax. , purer and more original. . Vue is implemented through instructions in a separate template that is separated from the component JS code. For example, conditional statements require v-if to achieve this. This approach seems a bit unique and will mess up the HTML. .

3. Features of React

Insert image description here

4. React introduction and description

		1.用于动态构建用户界面的 JavaScript 库(只关注于视图)
		2.由Facebook开源

5. Reasons why React is efficient

		1.使用虚拟(virtual)DOM, 不总是直接操作页面真实DOM。
		2.DOM Diffing算法, 最小化页面重绘。
		关于虚拟DOM:
		1.本质上是object类型的对象(一般对象)
		2.虚拟DOM比较轻,真实DOM比较重。因为虚拟DOM

6.The power of React

high speed

It does not directly operate on the DOM. It introduces a concept called virtual DOM, which is placed between the JavaScript logic and the actual DOM and has good performance.

Very good cross-browser compatibility

Virtual DOM helps us solve cross-browser problems. It provides us with a standardized API, which is no problem even in IE8.

All are components:

Componentized code is more modular, easier to reuse, and more maintainable.

One-way data flow

Flux is an architecture for creating one-way data layers in JavaScript applications, conceptualized by Facebook along with the development of the React view library.

Good compatibility

For example, RequireJS is used for loading and packaging, while Browserify and Webpack are suitable for building large applications. They make difficult tasks less daunting

2. React basic format

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="./js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="./js/react-dom.development.js"></script>
    <!-- 引入 babel
            1.es6 ==> es5
            2.jsx ==>js -->

    <script src="./js/babel.min.js"></script>
    <script type="text/babel">
            // 1.创建虚拟 dom
            const VDOM = <h1>hello word</h1>

            // 2.渲染到页面中的指定dom
            // ReactDOM.render(虚拟dom,真实dom)
            ReactDOM.render(VDOM,document.getElementById('test'))


    </script>
</body>

</html>

Explanation: First we need to complete the basic introduction of react. Then first create a virtual dom and then render the virtual dom into the real dom in the specified element.

1. What is virtual dom?

What is virtual DOM? In React, the result of render execution is not a real DOM node, but a lightweight JavaScript object, which we call virtual DOM. Virtual DOM is a highlight of React, with batching and efficient Diff algorithm.

2. Why create a virtual dom?

We know that the concept of virtual DOM was first proposed by Facebook's React team and is also one of the core concepts of the React framework. Its function is to describe the real DOM structure in memory in the form of js, so that when the page content needs to change, React can calculate how to operate the real DOM at the minimum cost by comparing the previous and later virtual DOMs.

3. React is also divided into two creation methods

1. Use js to create

Disclaimer Not recommended. Lots of code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="../js/react-dom.development.js"></script>

    <script type="text/javascript">
        // 1.创建虚拟 dom
        // const VDOM = React.createElement(标签名,标签属性,标签内容)
        const VDOM = React.createElement('h1', {
    
     id: "title" }, React.createElement('span',{
    
    },"hello react"))


        // 2.渲染到页面中的指定dom
        // ReactDOM.render(虚拟dom,真实dom)
        ReactDOM.render(VDOM, document.getElementById('test'));


    </script>
</body>

</html>

2.Create using jsx method

Statement: It is recommended to use it, it will automatically convert to js format and the code is concise (it does not have this pointer and you need to bind this yourself or use an arrow function)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="../js/react-dom.development.js"></script>
     <!-- 引入 babel
            1.es6 ==> es5
            2.jsx ==>js -->

            <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        // 1.创建虚拟 dom
        // const VDOM = React.createElement(标签名,标签属性,标签内容)
        const VDOM = (
            <h1>hello
                <span>react-dom</span>
            </h1>
        )


        // 2.渲染到页面中的指定dom
        // ReactDOM.render(虚拟dom,真实dom)
        ReactDOM.render(VDOM, document.getElementById('test'));


    </script>
</body>

</html>

4. Grammar rules of jsx

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .title{
    
    
            color: aliceblue;
        }
    </style>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入 babel
            1.es6 ==> es5
            2.jsx ==>js -->

    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        let myData = 'Student';
        let idData = 'zhongwu';
        // 1.创建虚拟 dom
        // const VDOM = React.createElement(标签名,标签属性,标签内容)
        const VDOM = (
            <div>
                <h1 className="title" id={
    
    idData}>
                    hello,                                                            
                    <span>{
    
     myData }</span>
                    <input type="text"></input>
                    <Good />
                </h1>
            </div>
        )


        // 2.渲染到页面中的指定dom
        // ReactDOM.render(虚拟dom,真实dom)

        ReactDOM.render(VDOM,document.getElementById('test'));

    </script>
</body>

</html>

Note:
The syntax rules of jsx:
1. When defining virtual dom, do not use quotation marks;
2. When mixing js expressions in tags, use {}
3. Do not use class when specifying the class name of the style, use className;
4. Inline Style should be written in the form of style={ {key:value}}
5. There can only be one root element
6 All tags must be closed
7. The first letter of the tag:
1. If it starts with a lowercase letter, the tag will be changed Convert it into an html element with the same name and render it to the page.
If html does not have an element with the same name, an error will be reported.

                           2.若大写字母开头,react就会去渲染对应的组件,若组件没有定义,则报错;
        /

5. React definition components

**Disclaimer:** Componentization is the core idea of ​​React and the focus of our subsequent courses. The App we encapsulated earlier is itself a component: Componentization provides an abstraction that allows us to develop independent and reusable products. widgets to construct our application. Any application will be abstracted into a component tree. With the idea of ​​componentization, we must make full use of it in subsequent development. Split the page into small, reusable components as much as possible. This makes our code easier to organize and manage, and more scalable. React components are more flexible and diverse than Vue, and can be divided into many types of components in different ways: These concepts have a lot of overlap, but they mainly focus on the separation of data logic and UI display: Of course, there are many other concepts of components. : Such as asynchronous components, high-order components, etc., we will learn more about them later.

1. Functional components

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .title {
    
    
            color: aliceblue;
        }
    </style>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入 babel
            1.es6 ==> es5
            2.jsx ==>js -->

    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        // 1.创建函数式组件
        function MyComponent() {
    
    

                console.log(this)//undefined ,因为babel编译,开启了严格模式

            // 一定需要有返回值
            return <h2>我是用函数定义的组件(适用于【简单组件】的定义)</h2>
        }



        // 2.渲染到页面中的指定dom
        // ReactDOM.render(虚拟dom,真实dom)

        ReactDOM.render(<MyComponent />, document.getElementById('test'));

        /*
            执行ReactDOM.render()方法之后,发生了什么?

            1.React解析了组件标签,找到了对应的组件
            2.发现这个组件是一个函数定义的 随后调用改函数,生成了一个虚拟dom
            3.最后将虚拟dom转化为真实dom,呈现在页面中
        
        
        */


    </script>
</body>

</html>

2. Class components

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      
    </style>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入 babel
            1.es6 ==> es5
            2.jsx ==>js -->

    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        // 1.创建一个 类式组件
        class MyComponent extends React.Component{
    
    

            //render方法是放在原型上
            // render中的this是谁?  ---实例对象
            render(){
    
    
                console.log('render中的this',this)
                return  <h2>我是用类定义的组件(适用于【复杂组件】的定义)</h2>
            }

        }
 
        ReactDOM.render(<MyComponent />, document.getElementById('test'));

         /*
            执行ReactDOM.render()方法之后,发生了什么?

            1.React解析了组件标签,找到了对应的组件
            2.发现这个组件是一个类定义的 随后new出来一个实例对象并通过该实例对象调用原型上的render方法
            3.最将render() 返回的内容生成一个虚拟dom
            4.最后将虚拟dom转化为真实dom,呈现在页面中
        
        
        */
     
        let c = new MyComponent();
        console.log(c)

    </script>
</body>

</html>

3. The difference between functional components and class components

1. A function component is a pure function that receives a props object and returns a react element; while a class component needs to inherit React.Component and create a render function to return a react element.
2. Function components do not have a life cycle and state, but class components do.
3. Official recommendations are to use functional components

6. Three major attributes of component instances

1.state

Statement:
State (state) is data, which is private data inside the component. It can only be used inside the component. The
value of state is an object, indicating that there can be multiple data in a component.
Get the state through this.state
and modify the state data through setState ( Note: The state data is read-only and cannot be modified. If you want to modify it, use setState)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>
    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持忍让传统操作dom -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入 babel
            1.es6 ==> es5
            2.jsx ==>js -->

    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        // 1.创建一个 类式组件
        class Weather extends React.Component {
    
    
            state = {
    
     isTian: true, wind: '微风' };

            render() {
    
    
                let {
    
     isTian, wind } = this.state;
                return <h2 onClick={
    
    this.changewWeather}>今天天气很爽 {
    
    isTian ? "不冷" : "不热"},{
    
    wind}</h2> //istian
            }




            changewWeather = () => {
    
    

                let {
    
     isTian } = this.state;

                this.setState({
    
     isTian: !isTian })//这里的修改,是覆盖还是合并?


            }

        }

        ReactDOM.render(<Weather />, document.getElementById('test'));





    </script>
</body>

</html>

2.props

**Statement:**Transfer data

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .title {
    
    
        color: aqua;
    }
</style>

<body>
    <div id="test">

    </div>
    <div id="test1">

    </div>
    <div id="test2">

    </div>
    <!-- 引入React核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 操作dom -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入babel ES6==>ES5  JSX==>JS -->
    <script src="../js/babel.min.js"></script>
    <script type="text/babel">
        class Weather extends React.Component {
    
    
            constructor(props) {
    
    //是否接受,取决于是否使用外部数据
                super(props)//只能上面接受了props,super()就去传递,否则后续的使用,可能就会出现问题

            }
            static propTypes = {
    
    
                name: PropTypes.string.isRequired,//限制name为字符串类型,必填
                // age: PropTypes.number,
                sex: PropTypes.string,
                speak: PropTypes.func
            }
            static defaultProps = {
    
    
                sex: '男',
            }

            render() {
    
    
                let {
    
     name, age, sex } = this.props
                return (
                    <ul>
                        <li>姓名:{
    
    name}</li>
                        <li>性别:{
    
    sex}</li>
                        <li>年龄:{
    
    age + 1}</li>
                    </ul>
                )
            }
        }
        /*
            问题:
                1.数据类型是否有对应的限制?
                2.数据的数量 批量传输可以使用展开运算符
        */
        ReactDOM.render(<Weather name="tom" age={
    
    26} sex="女" />, document.getElementById('test'))

    </script>
</body>

</html>

3、ref

**Disclaimer:** In a typical React data flow, props are the only way for parent components to interact with child components. To modify a child component, you need to re-render it with new props. However, there are situations where you need to force modification of a subcomponent outside of the typical data flow. The modified subcomponent may be an instance of a React component or a DOM element. For both cases, React provides the use of ref to solve it.

Author: Smart Girl Wants to Be Bald
Link: https://juejin.cn/post/7047113456993959972
Source: Rare Earth Nuggets
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        class Person extends React.Component {
    
    

            showData = () => {
    
    
                //转款专用:每一个ref都是唯一的,存在this.refs中
                let {
    
     ipt } = this.refs;
                alert(ipt.value)
            }

            getData=()=>{
    
    
                let {
    
     ipt1 } = this.refs;
                alert(ipt1.value)
            }
            render() {
    
    
                return (
                    <div>
                        <input ref='ipt' type="text" placeholder="请输入数量" />
                        <button onClick={
    
    this.showData}>点我提示左侧的数据</button>
                        <input onClick={
    
    this.getData} ref='ipt1' type="text" placeholder="请输入数量" />
                    </div>
                )
            }
        }


        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

7. Event handling

Statement: 1. Specify the event processing function through the onXxx attribute (note the case)
1) React uses custom (synthetic) events instead of the native DOM events used - for better compatibility
2) The events in React are Processed through event delegation (delegated to the outermost element of the component) - for more efficiency
2. Obtain the DOM element object where the event occurred through event.target - do not overuse refs

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        class Person extends React.Component {
    
    





            myRef = React.createRef(); //容量为1,只能存一个,多余会覆盖前者
            myRef1 = React.createRef();

            showData = (event) => {
    
    
                alert(this.myRef.current.value)
                console.log(event.target)
            }
            showData1 = () => {
    
    
                alert(this.myRef1.current.value)
            }

// 回调函数
            // 1.自己写的函数
            // 2.不是自己调用的
            // 3.这个函数最后执行了

            render() {
    
    
                return (
                    <div>
                        {
    
    /* 这里是jsx注释 */}
                        <input ref={
    
    this.myRef} type="text" placeholder="请输入数量" />
                        <button onClick={
    
    this.showData}>点我提示左侧的数据</button>
                        <input onBlur={
    
    this.showData1} ref={
    
    this.myRef1} type="text" placeholder="请输入数量" />
                    </div>
                )
            }
        }


        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

8. React collection form

1. Uncontrolled components

**Statement:** Manually read the data in the form input box only when needed

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        class Person extends React.Component {
    
    

         
            handler=(event)=>{
    
    
                event.preventDefault();//阻止默认事件 --- 阻止表单跳转
                    let {
    
    username,password} = this;
                    alert(`你输入的名字${
     
     username.value},密码是${
     
     password.value}`)
            }
            render() {
    
    
                return (
                    <div>
                        <form action="https://www.baidu.com" onSubmit={
    
    this.handler}>
                            用户名:<input type="text" name='username' ref={
    
     c =>this.username=c} />
                            密码:<input type="text" name="password" ref={
    
     c =>this.password=c } />
                            <button type="submit">登录</button>
                        </form>
                    </div>
                )
            }
        }


        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

2. Controlled components

**Statement:** Form item input data can be automatically collected into status.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">




        //受控组件
        class Person extends React.Component {
    
    
            //初始化状态
            state = {
    
    
                username: '',//用户名
                password: ''//密码
            }
            //保存用户名到状态中
            saveUsername = (event) => {
    
    
                this.setState({
    
     username: event.target.value })
            }

            //保存密码到状态中
            savePassword = (event) => {
    
    
                this.setState({
    
     password: event.target.value })
            }


            //表单提交回调
            handler = (event) => {
    
    
                event.preventDefault();//阻止默认事件 --- 阻止表单跳转
                let {
    
     username, password } = this.state;
                alert(`你输入的名字${
     
     username},密码是${
     
     password}`)
            }
            render() {
    
    
                return (
                    <div>
                        <form action="https://www.baidu.com" onSubmit={
    
    this.handler}>
                            用户名:<input type="text" name='username' onChange={
    
    this.saveUsername} />
                            密码:<input type="text" name="password" onChange={
    
    this.savePassword} />
                            <button type="submit">登录</button>
                        </form>
                    </div>
                )
            }
        }


        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

9. Higher-order functions

1.Higher-order functions

Statement:
Higher-order function: If a function meets any of the following two specifications, then it belongs to a higher-order function
1. If function A accepts a parameter as a function, then A can be called a higher-order function
2 .If the return value of function A is still a function, then A can also be called a higher-order function

    常见的高阶函数:Promise,setTimeout,arr.map回调函数等等

Function currying: By continuing to call the function and returning the value to the function, it is possible to receive parameters multiple times and the most unified processing function coding form

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

/*
region


                 function sum(a){
    
    
                return (b)=>{
    
    
                    return (c)=>{
    
    
                        return a+b+c;
                    }
                }
            }

*/


        //受控组件
        class Person extends React.Component {
    
    
            //初始化状态
            state = {
    
    
                username: '',//用户名
                password: ''//密码
            }
            //保存用户名到状态中
            saveUsername = (event) => {
    
    
                this.setState({
    
     username: event.target.value })
            }

            //保存密码到状态中
            savePassword = (event) => {
    
    
                this.setState({
    
     password: event.target.value })
            }


            //保存表单数据到状态中
            saveFormData = (dataType) => {
    
    //这里传来的是标识  标识当前标签
                return (event)=>{
    
     //这里的回调谁执行?? input标签的 onchange事件
                   
                    // console.log(event.target.value,'@@@')
                        this.setState({
    
    
                            [dataType]: event.target.value
                        })
                        // console.log(dataType) // username password 
                }

            }
            //表单提交回调
            handler = (event) => {
    
    
                event.preventDefault();//阻止默认事件 --- 阻止表单跳转
                let {
    
     username, password } = this.state;
                alert(`你输入的名字${
     
     username},密码是${
     
     password}`)
            }
            render() {
    
    
                return (
                    <div>
                        <form action="https://www.baidu.com" onSubmit={
    
    this.handler}>
                            用户名:<input type="text" name='username' onChange={
    
    this.saveFormData('username')} />
                            密码:<input type="text" name="password" onChange={
    
    this.saveFormData('password')} />
                            <button type="submit">登录</button>
                        </form>
                    </div>
                )
            }
        }


        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

2. Function currying

Statement:
Currying is a technique that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns a result.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

     


        //受控组件
        class Person extends React.Component {
    
    
            //初始化状态
            state = {
    
    
                username: '',//用户名
                password: ''//密码
            }
            //保存用户名到状态中
            saveUsername = (event) => {
    
    
                this.setState({
    
     username: event.target.value })
            }

            //保存密码到状态中
            savePassword = (event) => {
    
    
                this.setState({
    
     password: event.target.value })
            }


            //保存表单数据到状态中
            saveFormData = (dataType, event) => {
    
    //这里传来的是标识  标识当前标签

                this.setState({
    
    
                    [dataType]: event.target.value
                })



            }
            //表单提交回调
            handler = (event) => {
    
    
                event.preventDefault();//阻止默认事件 --- 阻止表单跳转
                let {
    
     username, password } = this.state;
                alert(`你输入的名字${
     
     username},密码是${
     
     password}`)
            }
            render() {
    
    
                return (
                    <div>
                        <form action="https://www.baidu.com" onSubmit={
    
    this.handler}>
                            用户名:<input type="text" name='username' onChange={
    
    event => this.saveFormData('username', event)} />
                            密码:<input type="text" name="password" onChange={
    
    event => this.saveFormData('password', event)} />
                            <button type="submit">登录</button>
                        </form>
                    </div>
                )
            }
        }


        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

10. Component life cycle

1. What is the life cycle of a component:

The process from when a component is created to when it is mounted and run on the page, to when it is uninstalled when not in use

2. The role of the hook function:

Provides opportunities for developers to operate components at different stages.

3. The meaning of life cycle:

Helps understand how components operate,
complete more complex component functions,
analyze the causes of component errors, etc.

4. Life cycle usage scenarios

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        // 1.创建虚拟 dom


                // 1. 生命周期回调函数 === 生命周期钩子函数 === 生命周期函数 === 生命周期钩子

        class Person extends React.Component {
    
    
            state = {
    
    
                opacity: 1
            }

            constructor(){
    
    
                super();
                console.log('constructor')
            }

            //组件将要挂载
            componentWillMount(){
    
    
                console.log("componentWillMount")
            }

            //组件将要卸载
            componentWillUnmount(){
    
    
                console.log("啊 我Neo写咋")
                clearInterval(this.timer)
            }

            //组件挂载完成之后
            componentDidMount() {
    
    
                console.log("componentDidMount")
                setInterval(() => {
                    // 获取原状态

                    let { opacity } = this.state;
                    opacity -= 0.1;
                    if (opacity <= 0) opacity = 1;
                    //设置新透明度
                    this.setState({ opacity });

                }, 200)

            }

            death=()=>{
                //卸载组件
                ReactDOM.unmountComponentAtNode(document.getElementById('test'))
            }
            render() {
    
    
                console.log("render")

                return (
                    <div>
                        <span style={
    
    {
    
     opacity: this.state.opacity } } >学不会React怎么办</span>
                        <button onClick={
    
    this.death}>按钮</button>
                    </div>
                )
            }


        }
        // 2.渲染到页面中的指定dom
        ReactDOM.render(<Person />, document.getElementById('test'))

    </script>
</body>

</html>

5.react life cycle (old)

Insert image description here

Three phases of the life cycle (old)
1. Initialization phase: triggered by ReactDOM.render() - initial rendering
1.constructor()
2.componentWillMount()
3.render()
4.componentDidMount()
2. Update phase: triggered by This.setSate() inside the component or the parent component re-render triggers
1.shouldComponentUpdate()
2.componentWillUpdate()
3.render()
4.componentDidUpdate() 3. Uninstall the component: 1.componentWillUnmount()
is triggered by ReactDOM.unmountComponentAtNode( )

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">


        /*
        1. 初始化阶段: 由ReactDOM.render()触发---初次渲染
          1.constructor()
          2.componentWillMount()
          3.render()
          4.componentDidMount() === >常用:
                            一般在这个钩子中做一些初始化的事情:例如:开启定时器,发送网络请求


        2. 更新阶段: 由组件内部this.setSate()或父组件重新render触发
            1.shouldComponentUpdate()
            2.componentWillUpdate()
            3.render()   ===》必须使用
            4.componentDidUpdate() 


        3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
            1.componentWillUnmount() ===》常用
                一般在中国函数中做一些收尾的事,例如:关闭定时器 取消订阅

        */

        class Person extends React.Component {
    
    

            state = {
    
     count: 0 }

            // 点我
            add = () => {
    
    
                //获取原状态
                let {
    
     count } = this.state;
                // 更新状态
                this.setState({
    
     count: count + 1 });
            }

            // 卸载组件
            death = () => {
    
    
                ReactDOM.unmountComponentAtNode(document.getElementById('test'))
            }

            force = () => {
    
    
                this.forceUpdate()
            }

            // 数据更新的 '阀门'
            shouldComponentUpdate = () => {
    
    
                console.log("count ------ shouldComponentUpdate")
                return true; //这里必须有返回值,其次返回值默认为true
            }

            // 组件将要更新的钩子
            componentWillUpdate() {
    
    
                console.log("count ----   componentWillUpdate")
            }

            // 组件更新完毕的钩子
            componentDidUpdate() {
    
    
                console.log("count ---- componentDidMount")
            }
            render() {
    
    
                return (
                    <div>
                        <h2>当前求和为:{
    
    this.state.count}</h2>
                        <button onClick={
    
    this.add}>点我+1</button>
                        <button onClick={
    
    this.death}>卸载组件</button>
                        <button onClick={
    
    this.force}>不更改任何状态中的数据,强制更新</button>
                    </div>
                )
            }
        }


        // 父组件

        class A extends React.Component {
    
    
            state = {
    
     carName: "电动车" }
            changeCar = () => {
    
    
                this.setState({
    
     carName: '飞机' });
            }
            render() {
    
    
                console.log("render")
                return (
                    <div>
                        <span>我是a组件</span>
                        <button onClick={
    
    this.changeCar}>换车</button>
                        <B carName={
    
    this.state.carName} />
                    </div>
                )
            }
        }

        // 子组件
        class B extends A {
    
    

            //组件将要接收新的props 的钩子
            componentWillReceiveProps() {
    
    
                console.log("B ---- componentWillReceiveProps ")
            }
            // 数据更新的 '阀门'
            shouldComponentUpdate = () => {
    
    
                console.log("count ------ shouldComponentUpdate")
                return true; //这里必须有返回值,其次返回值默认为true
            }

            // 组件将要更新的钩子
            componentWillUpdate() {
    
    
                console.log("count ----   componentWillUpdate")
            }

            // 组件更新完毕的钩子
            componentDidUpdate() {
    
    
                console.log("count ---- componentDidMount")
            }
            render() {
    
    

                return (
                    <div>
                        我是b组件,接收到的车是:{
    
    this.props.carName}
                    </div>
                )
            }
        }

        ReactDOM.render(<A />, document.getElementById('test'))

    </script>
</body>

</html>

6.React life cycle (new)

Insert image description here

Three stages of life cycle (new)

  1. Initialization phase: Triggered by ReactDOM.render() - initial rendering
    1.constructor()
    2.getDerivedStateFromProps
    3.render()
    4.componentDidMount()
    2. Update phase: triggered by this.setSate() inside the component or re-render of the parent component
    1.getDerivedStateFromProps
    2.shouldComponentUpdate()
    3.render()
    4.getSnapshotBeforeUpdate
    5.componentDidUpdate()
    3. Uninstall the component: Triggered by ReactDOM.unmountComponentAtNode()
    1.componentWillUnmount()
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref</title>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入 React 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持 react 操作 DOM -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引入babel:
            1. ES6 ==> ES5
            2. jsx ==> js
    -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">


        /*
        1. 初始化阶段: 由ReactDOM.render()触发---初次渲染
          1.constructor()
          2.componentWillMount()
          3.render()
          4.componentDidMount() === >常用:
                            一般在这个钩子中做一些初始化的事情:例如:开启定时器,发送网络请求


        2. 更新阶段: 由组件内部this.setSate()或父组件重新render触发
            1.shouldComponentUpdate()
            2.componentWillUpdate()
            3.render()   ===》必须使用
            4.componentDidUpdate() 


        3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
            1.componentWillUnmount() ===》常用
                一般在中国函数中做一些收尾的事,例如:关闭定时器 取消订阅

        */

        class Person extends React.Component {
    
    

            state = {
    
     count: 0 }

            // 点我
            add = () => {
    
    
                //获取原状态
                let {
    
     count } = this.state;
                // 更新状态
                this.setState({
    
     count: count + 1 });
            }

            // 卸载组件
            death = () => {
    
    
                ReactDOM.unmountComponentAtNode(document.getElementById('test'))
            }

            force = () => {
    
    
                this.forceUpdate()
            }

            // 数据更新的 '阀门'
            shouldComponentUpdate = () => {
    
    
                console.log("count ------ shouldComponentUpdate")
                return true; //这里必须有返回值,其次返回值默认为true
            }

            // 组件将要更新的钩子
            componentWillUpdate() {
    
    
                console.log("count ----   componentWillUpdate")
            }

            // 组件更新完毕的钩子
            componentDidUpdate() {
    
    
                console.log("count ---- componentDidMount")
            }
            render() {
    
    
                return (
                    <div>
                        <h2>当前求和为:{
    
    this.state.count}</h2>
                        <button onClick={
    
    this.add}>点我+1</button>
                        <button onClick={
    
    this.death}>卸载组件</button>
                        <button onClick={
    
    this.force}>不更改任何状态中的数据,强制更新</button>
                    </div>
                )
            }
        }


        // 父组件

        class A extends React.Component {
    
    
            state = {
    
     carName: "电动车" }
            changeCar = () => {
    
    
                this.setState({
    
     carName: '飞机' });
            }

            static getDerivedStateFromProps(props,state){
    
    

                // 这里必须要一个返回值 ==》 state or null
            // 这里的state会覆盖原本的状态,并且后续也无法修改

            // 能将外部的接受的props 赋值给 组件自身的 state
            // 如果你希望自身的state 一直 全部依赖于外部的props,那么可以使用这个生命周期函数
             return{
    
    carName:'qq'}
            }


            // 获取数据
            getSnapshotBeforeUpDate(prevState,prevProps){
    
    

            }
            render() {
    
    
                console.log("A --- render")
                return (
                    <div>
                        <span>我是a组件</span>
                        <button onClick={
    
    this.changeCar}>换车</button>
                        <B carName={
    
    this.state.carName} />
                    </div>
                )
            }
        }

        // 子组件
        class B extends A {
    
    

            //组件将要接收新的props 的钩子
            componentWillReceiveProps() {
    
    
                console.log("B ---- componentWillReceiveProps ")
            }
            // 数据更新的 '阀门'
            shouldComponentUpdate = () => {
    
    
                console.log("count ------ shouldComponentUpdate")
                return true; //这里必须有返回值,其次返回值默认为true
            }

            // 组件将要更新的钩子
            componentWillUpdate() {
    
    
                console.log("count ----   componentWillUpdate")
            }

            // 组件更新完毕的钩子
            componentDidUpdate() {
    
    
                console.log("count ---- componentDidMount")
            }
            render() {
    
    

                return (
                    <div>
                        我是b组件,接收到的车是:{
    
    this.props.carName}
                    </div>
                )
            }
        }

        ReactDOM.render(<A />, document.getElementById('test'))

    </script>
</body>

</html>

7. The important hook

1.render: Initialize rendering or update rendering call
2.componentDidMount: Turn on listening and send ajax request
3.componentWillUnmount: Do some finishing work, such as: clean up timer

8. The soon-to-be-abandoned hook

1.componentWillMount
2.componentWillReceiveProps
3.componentWillUpdate
will cause a warning when used now. The next major version needs to be prefixed with UNSAFE_ before it can be used. It may be completely abandoned in the future and is not recommended.


Summarize

The above is the basic knowledge of react, and there are comments in the code. React scaffolding will be released in the next issue. If you like it, prove that you have been here^ - ^

Guess you like

Origin blog.csdn.net/www61621/article/details/129795843