S
S
Stepan2015-11-10 17:27:29
JavaScript
Stepan, 2015-11-10 17:27:29

Is there a way to not bind every function that needs this in ES6 React?

constructor (props) {
        super(props);
        this.toggleMenu = this.toggleMenu.bind(this);
        this.showSidebar = this.showSidebar.bind(this);
        this.resize = this.resize.bind(this);
        this.toggleMenuByClick = this.toggleMenuByClick.bind(this);
        this.showSidebarByClick = this.showSidebarByClick.bind(this);
        this.state = {
            toggleMenu: false,
            showSidebar: false,
            height: 'auto'
        };
    }

Example

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-11-10
@iNikNik

In babel marked stage-0 there is such a thing - https://github.com/jeffmo/es-class-static-properti...
It allows you to do this:

class MyClass {
  foo = () => {
    console.log('foo a = ', this.a);
  }

  bar = () => {
    this.a = 10;
    setTimeout(this.foo, 10); // Мы не биндим foo на this
  }
}

const o = new MyClass();
const bar = o.bar; // и тут тоже не биндим

bar(); // выводит "foo a = 10"

A
Alexey Zuev, 2015-11-10
@yurzui

Binding to methods of React class (ES7 included)
I like using arrow functions and class properties from es7

onMouseMoveHandler = (e) => {
    if (this.state.active) {
    ....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question