score:7

Accepted answer

Don't know about Typescript, but I'm guessing it's the same thing as when creating components using the similar ES2015 syntax which will need a constructor, and function binding to make a reference to this.onWheel work.

So in ES2015,

class foo extends React.Component {
  constructor(props) {
    super(props);
    // Magic happens here:
    this.onWheel = this.onWheel.bind(this)
    // Now each instance of foo can use this.onWheel
  }

  onWheel () {
    ....
  }

  render (){
    ....
  }
}

score:1

The simple thing would be converting it into an arrow function which binds automatically:

 public onWheel = (e: React.WheelEvent): void => {
    e.preventDefault();
    e.stopPropagation();

    //Do stuff with the div, and yes you can work with 'this' in this function
    this.div;
}

score:2

onWheel= { this.onWheel}
onWheel={this.onWheel.bind(this)}

score:5

Another solution if you don't want to bind each function in the constructor is to use lambdas:

class foo extends React.Component {
  constructor(props) {
    super(props);
  }

  // The lambda creates a lexical scope so it's autobound
  onWheel = () => {
    ....
  }

  render () {
    ....
  }
}

You can read more here.


Related Query

More Query from same tag