简体   繁体   中英

reactjs typescript event this undefined

I got the following component written in typescript. (type definitions from definitelytyped.org). I got the onWheel event bound to a function. But when ever it is fired this is undefined, so how am I supposed to access the referenced element this.div and if I would want/need to change the state how should do that?

import React = require('react');

interface fooProps {
    src: string;
}

class foo extends React.Component<fooProps, {}>
{
    private div: HTMLDivElement;

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

        //Do stuff with the div, but 'this' is undefined!!
        this.div;
    }
    public render(): JSX.Element {
                return (
            <div ref={(ref) => this.div = ref} onWheel= { this.onWheel} >
                <img src={ this.props.src } />
                </div >)
    }
}

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 (){
    ....
  }
}

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 .

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM