Study notes-react basic function learning


The react framework is currently a more popular framework, which is mainly used for larger projects. The react framework is similar to the vue framework. The following mainly learns how the following vue instructions are implemented in react.

1.react download: 

In the command window, download the react scaffolding package:

yarn global add create-react-app

 2. Create the project:

In the command window, enter the following to create a react project:

create-react-app  项目名

3. Understand the project:

Use webStorm, VS Code or HBulider to open your project. You can see some files, among them

The package.json contains some basic configuration of the project, such as how to start, package the project, and the dependent packages of the project.

The src folder is our main place to write code. In src, the index.js file is the root instance, and the root component App is rendered to the mount point in index.html in the public folder. Its content is relatively fixed.

// 使用jsx对象(例如:<App />)时,必须引入react
import React from 'react';
import ReactDOM from 'react-dom';
// 导入根组件
import App from './App.jsx';

// 第一个参数;要渲染什么。第二个参数:要渲染到哪里
ReactDOM.render( <App />, document.getElementById('root'));

App.jsx in the src folder is the root component. There are two ways to define root components: class components and function components.

What is a jsx object? Relative to the template in vue.

The react component must specify a render function, which must return a jsx object or null.

The following uses class components.

// react组件的自定义就是要继承自React.Component的类
import React, { Component } from 'react';

class App extends Component {
    constructor() {
        super();                  // 可以使用父组件中的构造函数
        this.state = {            // 放需要渲染的数据
                            
        }
    }
    render() {                    // return中写html代码,返回jsx对象
        return {(                 // 写html代码时,可以用()包裹
            <div><div>            // 只有一个根节点
        )};
    }
}

The App.css in the src folder is to modify the style of the root component, but if multiple css folders have the same class value, it will cause rendering confusion. So we generally use App.module.css to find the exact style we need. 

import style from './App.module.css';     // 导入样式文件

render() {
    return {
        <div className={style["container"]></div>
    };
}

 4. Basic function realization:

In the following functions, the data used comes from this.state in the constructor. The function comes from a custom function at the same level as the constructor and render.

1. Similar to the v-text command in vue:

<span>{this.state.name}</span>

2. Similar to the v-if instruction in vue:

<div>
    {this.state.isShow && (    // this.state.isShow为真时,显示后面的内容
        <div>显示内容</div>
    )}
</div>

3. Similar to the v-if + v-else instruction in vue:

<div>
    {this.state.isShow ? (
        <div>为真显示的内容</div>
    ) : (
        <div>为假显示的内容</div>
    )}
</div>

4. Similar to the v-if + v-else-if + v-else instruction in vue:

This instruction can be implemented indirectly through a function, but the function must return a jsx object.

// render()函数周围
judge() { return jsx对象 }
// render()函数returnjsx对象中
<div>
    {this.judge}
</div>

5. Similar to the v-for instruction in vue:

<ul>
    {this.state.data.map((item,i) => (        // 简单类型的数组
        <li key={i}>{item}</li>
    ))}
</ul>

6. Similar to the v-show command in vue:

It can't be realized directly, it can be realized by dynamically changing the class value. Set a class value show: display block in the CSS; another class value hidden: display: none; switch the class back and forth to implement the v-show command.

<span className={this.state.isShow ? style["show"] : style["hidden"]}>显示</span>

7. Similar to the v-bind instruction in vue:

It is possible to realize the simultaneous existence of dynamic and static class values.

// 共有两种方式实现:
<span className={["aaa", this.state.isShow ? style["show"] : ""].join(" ")}>显示</span>

<span className={`aaa ${ this.state.isShow ? style["show"] : "" }`>显示</span>

8. Similar to the v-on instruction in vue:

Bind events to the label. Use on+event name, for example, click event onClick.

Event binding does not pass parameters (by default event object e):

<button onClick={this.clickHandler}>点我</button>

Event binding pass parameters (written as an arrow function):

<button onClick={() => this.clickHandler2(100)}>点我</button>

When using event binding, you also need to pay attention to the pointing of the this pointer in the function. If you want the this pointer in the react event binding function to point to the current component itself, there are three methods:

1. Make a bind call in the constructor of the current component to bind this.

Advantages: When the function is passed from the parent component to the child component, the refresh of the function in the parent component will not cause the function in the child component to refresh meaninglessly.

Disadvantages: need to write additional code in the constructor

constructor() {
    super();
    this.state = {};
    this.clickHandler = this.clickHandler.bind(this)
}

clickHandler() {}

<button onClick={this.clickHandler}></button>

 2. When binding the function, bind the this pointer directly with bind.

Advantages: No need to write additional code in the constructor.

Disadvantages: When the function is passed from the parent component to the child component, the refresh of the function in the parent component will execute the bind expression to generate a new function that is the same as the previous one, but the child component will think this is a different function , Resulting in meaningless refresh of sub-components.

clickHandler() {}

<button onClick={this.clickHandler.bind(this)}></button>

3. Use ES6 class definition advanced features. When class definition functions, use arrow functions to bind this to the current component.

clickHandler = () => {};

<button onClick={this.clickHandler}></button>

 9. Modify the data in the state:

You must use this.setState() to modify the data in the state.

constructor() {
    super();
    this.state = {
        name: '张三',
        arr: [{id: 1, name: '张三'}, {id: 2, name: '李四'}],
        obj: { id: 3, name: '王五' }
    };
}

// 简单修改数据
this.setState({ name: '李四' });    // 运行后state中的name数据会发生改变'李四'
// 运行后state中obj中的值会变成'李四'
this.setState({ obj: Object.assign({}, this.state.obj, { name: '李四' }) })

// 操作arr
let arr = this.state.arr;
arr[0].name = "李四";
this.setState({ arr });
// 运行后,state中的arr的第一个对象中的name值为李四

This.setState() can be an object or a function. The difference is:

If it is an object (this.setState({})), no matter how many times it is iterated in the same piece of synchronous code, it will only perform the last operation.

If it is an object (this.setState(state => {})), the data in the later setState in the same synchronization code will use the result in the previous setState.

this.state = {
    a: 0,
    b: 0
}

for(let i = 0; i < 100; i++) {
    this.setState({ a: this.state.a + 1 });
    this.setState(state => { a: state.a + 1 });
}

// 操作执行结束后,a: 1, b: 100

 The above is the result of learning the react framework today.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109456824