Difference in passing callbacks into React component

Drew Cortright :

import React from 'react';
import ChildComponent from './ChildComponent';

class SampleComponent extends React.Component {

  sampleCallbackOne = () => {
    // does something
  };

  sampleCallbackTwo = () => {
    // does something
  };

  render() {
    return (
      <div>
          <ChildComponent
            propOne={this.sampleCallbackOne}
            propTwo={() => this.sampleCallbackTwo()}
          />
      </div>
    );
  }
}

export default SampleComponent;

In this example I have an onClick event that I am handling and saw that I can successfully pass this into the props of the component in two ways. I was wondering what exactly the difference is in both ways since they appear to function in the same manner. Why do both ways work?

keikai :

It is a common point that seems weird.

Refer details in document of handling-events

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);

handleClick() {
  console.log('this is:', this);
}

<button onClick={this.handleClick}>

If you don't add () behind this.handleClick, you need to bind this in your constructor, otherwise, you may want to use the next two methods:

A. public class field syntax

which is enabled by default in Create React App

handleClick = () => {
  console.log('this is:', this);
}

<button onClick={this.handleClick}>

B. arrow functions

which may cause performance problems and is not recommended, refer to the document above.

// The same on event handling but different in:
<button
  onClick={(e) => this.deleteRow(id, e)} // automatically forwarded, implicitly
/>
<button
  onClick={this.deleteRow.bind(this, id)} // explicitly
/>

Sample

Basically in our practice, we use public class field syntax with params which would look like below:

// No need to bind `this` in constructor
// Receiving params passed by elements as well as getting events of it
handler = (value: ValueType) => (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
  // Do something with passed `value` and acquired `event`
}
<NumberFormat
  ...
  onBlur={this.handler(someValue)} // Passing necessary params here
/>

We can share the handler function by passing different params to it.

// Justify via keyword of stored content in flat data structure
handler = (value: string) => (event: React.ChangeEvent<HTMLInputElement>, id: ValidationItems) => {
  // Do something with 
  // passed `value`, 
  // acquired `event`,
  // for each element diffenced via `id`
};

<YourComponent
  id="ID_1"
  value={store.name1}
  onChange={this.handler("name1")}
/>;

<YourComponent
  id="ID_2"
  value={store.name2}
  onChange={this.handler("name2")}
/>;

// ... more similar input text fields

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31981&siteId=1