V
V
Valery Chupurnov2017-05-16 10:51:38
Domain Name System
Valery Chupurnov, 2017-05-16 10:51:38

How to call a class method in React without bind?

Hello. Not so long ago, an article slipped through Habré about increasing the performance of React, and there was such an anti-pattern

<SearchCollection onClick={() => { Alert('Click'); }}/>

Like, the problem with this code is that with each rendering, a new arrow function is created, and as a result, the component thinks that it needs to be re-rendered too.
In the same article, they said that bind is identical in this case, since it creates a new function each time . Please tell me, what should I do if this.clickHandler needs to refer to props, for example, i.e. to this. And is it really worth worrying about?
<SearchCollection onClick={::this.clickHandler}/>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2017-05-16
@skoder

You can do this:

class MyComponent extends PureComponent {
  clickHandler = () => {
     // Так как это стрелочная функция - она будет забиндена при создании элемента (объекта)
  }

  render() {
    return (
      <SearchCollection onClick={this.clickHandler}/>
    )
  }
}

Or like this:
class MyComponent extends PureComponent {

  constructor(props, context) {
    super(props, context)
    this.clickHandler = this.clickHandler.bind(this)
  }

  clickHandler() {
  }

  render() {
    return (
      <SearchCollection onClick={this.clickHandler}/>
    )
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question