The first day of react learning (version 16.13.1)

Keywords: Front-end React

1. How react and dom are related

In our initialization project, index.html is the entry point of our project

In index.js corresponding to the main file of the project, our component is bound to the dom element

2. How to use this object correctly in the calling method

2.1. Actively bind this object when method is called (the best scheme, recommended scheme, because it can correctly pass parameters and avoid repeated dom rendering)

handleClick(...params){
    console.log(this,params)
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <div>
        <div>Analyze event delivery</div>
        <button onClick={this.handleClick.bind(this,1,2,3)}>
          {this.state.isToggleOn ? 'ON' : 'OFF'}
        </button>
      </div>
    );
  }

2.2 implement binding this object in construction method

import React from 'react';
export default class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isToggleOn: true };

    // In order to use 'this' in callbacks, this binding is essential
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <div>
        <div>Analyze event delivery</div>
        <button onClick={this.handleClick}>
          {this.state.isToggleOn ? 'ON' : 'OFF'}
        </button>
      </div>
    );
  }
}

2.3. Use the latest arrow function to keep this object unchanged during method definition

  handleClick=()=> {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <div>
        <div>Analyze event delivery</div>
        <button onClick={this.handleClick}>
          {this.state.isToggleOn ? 'ON' : 'OFF'}
        </button>
      </div>
    );
  }

2.4. Use arrow function to not change this object during method call

The problem with this syntax is that each time you render a LoggingButton, a different callback function is created. In most cases, this is fine, but if the callback function is passed in as a prop subcomponent, those components may be re rendered additionally. We usually recommend binding or using the class fields syntax in the constructor to avoid such performance problems.

  handleClick(){
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <div>
        <div>Analyze event delivery</div>
        <button onClick={()=>this.handleClick()}>
          {this.state.isToggleOn ? 'ON' : 'OFF'}
        </button>
      </div>
    );
  }

Posted by leafface on Thu, 07 May 2020 07:13:09 -0700