Home > Web Front-end > JS Tutorial > Some details of react that you may not have noticed! (Summarize)

Some details of react that you may not have noticed! (Summarize)

青灯夜游
Release: 2021-02-11 08:55:53
forward
2292 people have browsed it

Have you noticed these details in react? The following article summarizes some details of react that you may not have noticed. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Some details of react that you may not have noticed! (Summarize)

[Related tutorial recommendations: React video tutorial]

Some detailed knowledge points in react:

1. The use of get in components (as a getter for classes)

ES6 knowledge: class classes also have their own The getter and setter are written as follows:

Class Component {
     constructor() {
         super()
         this.name = ''
    }    
    
    // name的getter
    get name() {
        ...
    }

    // name的setter
    set name(value) {
        ...
   }
}
Copy after login

The use of get in the react component is as follows:

/*
 *  renderFullName的getter 
 *  可以直接在render中使用this.renderFullName
 */ 

get renderFullName () {
  return `${this.props.firstName} ${this.props.lastName}`;
}

render() {
    return (
          <div>{this.renderFullName}</div>
    )   
}
Copy after login

So what is the use of getter in the react component? ?

constructor (props) {
    super()
    this.state = {};
  }

    
  render () {
    // 常规写法,在render中直接计算 
    var fullName = `${this.props.firstName} ${this.props.lastName}`;

    return (
      <div>
        <h2>{fullName}</h2>
      </div>
    );
  }
Copy after login
// 较为优雅的写法:,减少render函数的臃肿
renderFullName () {
  return `${this.props.firstName} ${this.props.lastName}`;
}

render () {
  var fullName = this.renderFullName()   <div>{ fullName }</div> }
Copy after login
// 推荐的做法:通过getter而不是函数形式,减少变量
get renderFullName () {
  return `${this.props.firstName} ${this.props.lastName}`;
}

render () {
   <div>{ this.renderFullName  }</div> 
}
Copy after login

If you know Vue, then you know the computed: {} computed property, which also uses getter at the bottom, but the getter of the object is not the getter of the class

// 计算属性,计算renderFullName
computed: {
    renderFullName: () => {
         return `${this.firstName} ${this.lastName}`;
    }
}
Copy after login

One advantage of Vue's computed is:

Computed properties are compared with function execution: there will be caching, reducing calculations ---> Computed properties will only be re-evaluated when its related dependencies change. .

This means that as long as firstName and lastName have not changed, multiple accesses to the renderFullName calculated property will immediately return the previous calculation results without having to execute the function again.

So does react’s getter also have the advantage of caching? ? ? The answer is: No, the getter in react does not do caching optimization!

2. Component attr and event execution sequence:

A. Parent-child components: In the form of props, the parent passes it to the child

 B. The same component: the back covers the front.

Relying on the above rules, in order to make attr have the highest weight, it should be placed in the lowest component, and the position should be as far back as possible.

<-- 父组件Parent | 调用子组件并传递onChange属性 -->
<div>
    <Child  onChange={this.handleParentChange} />
</div>

<-- 子组件Child | 接收父组件onChange, 自己也有onChange属性 -->
<input {...this.props} onChange={this.handleChildChange}  />
Copy after login

At this time, the onChange executed by the Child component only executes the handleChildChange event, and the handleParentChange event will not be executed.

  • 1. What if you only need to execute handleParentChange manage? ? In input {...this.props} and onChange={this.handleChildChange } Change position.
  • #2. What if both events need to be executed? ? In the child component HandlechildChange this.props.handleParentchange
# 3, The difference between method abbreviation in ES6 form: fn = () => {} and fn() {}:

export default Class Child extends Component {
    constructor (props) {
        super()
        this.state = {};
   }

    // 写法1,这是ES6的类的方法写法
    fn1() {
         console.log(this)
        // 输出 undefined
    }
 
    // 写法2,这是react的方法写法
    fn2 = () => {
         console.log(this)
         // 输出:Child {props: {…}, context: {…}, refs: {…}, …}
    }

   render () {
        return (
          <div>
               <button onClick={this.fn1}>fn1方法执行</button >
               <button onClick={this.fn2}>fn2方法执行</button >
          </div>
         );
   }
}
Copy after login
There are two ways of writing, this within the function Pointing is different.

Are they not similar? ? , The following three situations are the same:

Case 1: When this is not used inside the function, the two are equal.

// 写法1,这是ES6的类的方法写法
    fn1() {
        return 1 + 1
    }
 
    // 写法2,这是react的方法写法
    fn2 = () => {
         return 1 + 1
    }
Copy after login
Case 2: When both are executed directly in render.

// 写法1,这是ES6的类的方法写法
    fn1() {
         console.log(this)
        // Child {props: {…}, context: {…}, refs: {…}, …}
    }
 
    // 写法2,这是react的方法写法
    fn2 = () => {
         console.log(this)
         // 输出:Child {props: {…}, context: {…}, refs: {…}, …}
    }

   render () {
        return (
          <div>
               <button onClick={() => {
                        this.fn1();
                }}>fn1方法执行</button >

               <button onClick={() => {
                        this.fn2();
                }}>fn2方法执行</button >
          </div>
         );
   }
Copy after login
Case 3: Give this.fn2.bind(this), bind this action context.

// 写法1,这是ES6的类的方法写法
    fn1() {
         console.log(this)
        // Child {props: {…}, context: {…}, refs: {…}, …}
    }
 
    // 写法2,这是react的方法写法
    fn2 = () => {
         console.log(this)
         // 输出:Child {props: {…}, context: {…}, refs: {…}, …}
    }

   render () {
        return (
          <div>
               <button onClick={this.fn1}>fn1方法执行</button >

               <button onClick={this.fn2.bind(this)}>fn2方法执行</button >
          </div>
         );
   }
Copy after login
Note, do not confuse it with the method abbreviation of the object in ES6. The following is the method abbreviation of the object Object:

Ruan Yifeng ES6: http://es6.ruanyifeng. com/#docs/object

#4. Array in list rendering

Reference: https: //doc.react-china.org/docs/lists-and-keys.html

The normal way to write jsx is to write syntax similar to HTML in render, with nested tags

< input />

, with js, use { curly brackets }.

But I don’t know if you have noticed that

Arrays can be nested inside tags

and render normally.

function NumberList(props) {
    const numbers = [1,2,3,4,5];

    // listItems是数组numbers通过map返回的,本质也是个数组。 
    const listItems = numbers.map((number) =>
        <li>{number}</li>
    );

    return (
        <ul>
             // 可以替换成 [ <li>1</li>,  <li>2</li>,  .....]
             {listItems}
        </ul>
    );
}
Copy after login
As shown above, the array inside the tag can be rendered correctly, then there is the following writing method:
renderItem(name) {
    const A = <li key={&#39;a&#39;}>A</li>, 
             B = <li key={&#39;b&#39;}>B</li>, 
             C = <li key={&#39;c&#39;}>C</li>, 
             D = <li key={&#39;d&#39;}>D</li>;
     let operationList;

     switch (name) {
        case 1:
            operationList = [A , B,  C]
           break;
        case 2:
            operationList = [B,  C, D]
            break;
        case 0:
           operationList = [A]
           break;
    }
    return operationList;
}

render() {
   // this.renderItem() 执行结果是数组
    return (
         <ul>{  this.renderItem() }</ul>
    )
}
Copy after login

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Some details of react that you may not have noticed! (Summarize). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template