编程知识 cdmana.com

On react synthetic event and its application

When you are in React When you see the following code in the component

<Button onClick={ 
    event =>{ 
     console.log('user click button') 
    }
  }> 
  Click Me</Button>

Have you ever thought about onClick Parameters of event What is it? ? The browser is it DOM Incident ?

If not , Why can we call event.stopPropagation() perhaps event.preventDefault() And get the expected effect ?


answer : This is a React In the original DOM A layer of encapsulation on events , be called SyntheticEvent( Composite event )


SyntheticEvent Is a class of objects , They all have the following properties / Method

boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
void persist()
DOMEventTarget target
number timeStamp
string type


SyntheticEvent There are two main features :

1. Compatible with all kinds of mainstream browsers DOM event

This is a React Provide a welfare feature ! We don't have to worry about this aspect of browser compatibility !



2. Event pooling mechanism

If you've heard of thread pools 、Java String constant pool, etc “ pool ” The concept of , You should be able to understand the meaning of event pools in seconds ( A lot of programming ideas are common )

Event pool can be interpreted as having a pool full of SyntheticEvent object , When necessary, the program will take some from the pool for use , Put it back into the pool after use .

The event pool mechanism means SyntheticEvent Objects are cached and reused , The goal is to improve performance , Reduce creating unnecessary objects . When SyntheticEvent When an object is fetched back into the event pool , Attributes will be erased 、 Reset to null.

therefore , We're writing React Remember when calling back the function Can't be event For asynchronous operations  —— When an asynchronous operation is actually executed ,SyntheticEvent The object may have been reset

The counter example is as follows :

import React, { Component } from "react";

class TextInput extends Component {
  state = {
    editionCounter0,
    valuethis.props.defaultValue,
  }
  //  because  setState  Is asynchronous operation ,event.target.value  It may have been reset at runtime 
  handleChange = event => 
    this.setState(prevState => ({ value: event.target.value, editionCounter: prevState.editionCounter + 1 }));

  render() {
    return (
      <span>Edited {this.state.editionCounter} times</span>
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange} // WRONG!
      />
    )
  }
}

Solution 1 : Use event.persist() Method

persist The literal translation of is persistence , namely  event.persist()  Method will event Kick out of event pool , So property values can always exist without being reset .

import React, { Component } from "react";

class TextInput extends Component {
  state = {
    editionCounter0,
    valuethis.props.defaultValue,
  }
  
  handleChange = event => {
    event.persist();  //  Persistence 
    this.setState(prevState => ({ value: event.target.value, editionCounter: prevState.editionCounter + 1 }));
  }

  render() {
    return (
      <span>Edited {this.state.editionCounter} times</span>
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange}
      />
    )
  }
}


The disadvantages of this scheme are obvious —— To give up SyntheticEvent Performance advantages of event pools , Improper use may cause performance problems



Solution 2 : Cache what you need in time event Property value

So-called ” cache “, In fact, it will correspond to event Attribute values are assigned to local variables —— The local variables are not reset .

import React, { Component } from "react";

class TextInput extends Component {
  state = {
    editionCounter0,
    valuethis.props.defaultValue,
  }
  
  handleChange = event => {
    const value = event.target.value; // value This local variable already holds the target value 
    this.setState(prevState => ({ value, editionCounter: prevState.editionCounter + 1 }));
  }

  render() {
    return (
      <span>Edited {this.state.editionCounter} times</span>
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange}
      />
    )
  }
}

Digression 1: Some students don't like to define temporary variables , Very much for the kind that looks very ” cool “ Of A long line of code ; Some students like to declare and define temporary variables , Make the code more readable , In this scenario , It happens to be able to avoid SyntheticEvent This pit of object reset .—— On the topic of declaring temporary variables , I prefer the latter a little bit , But too many temporary variables can sometimes reduce readability , It's difficult to grasp a certain degree .



summary

React SyntheticEvent Encapsulates and is compatible with browsers DOM event , The mechanism of event pool is adopted to improve the performance, and at the same time, it brings the disadvantage that it can not be used asynchronously —— Also good have 2 A simple solution .



Digression 2: This knowledge point interview will ask ?

Some companies with a strong technical atmosphere will still ask , Take a full look at React Basic knowledge of .

And if I was the interviewer, the probability would not be asked , I think this knowledge point is relatively unpopular , In the actual work, the common business development is not used much .

however , If you need to deal with a lot of events in a project , For example, support a large number of user gesture events such as Video playback 、 Picture editing etc. ,SyntheticEvent Still need to study deeply .

p.s. Learn more ( remember ) No harm at all , It's time to test brain capacity !


2229e33bd0d85d6dfe7b59b261757d3c.jpeg

Reference article :

https://reactjs.org/docs/events.html

https://medium.com/trabe/react-syntheticevent-reuse-889cd52981b6


版权声明
本文为[osc_ a949oaqo]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224141846058U.html

Scroll to Top