简体   繁体   English

reactjs typescript event this undefined

[英]reactjs typescript event this undefined

I got the following component written in typescript.我用打字稿编写了以下组件。 (type definitions from definitelytyped.org). (来自 absolutetyped.org 的类型定义)。 I got the onWheel event bound to a function.我将 onWheel 事件绑定到一个函数。 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?但是当它被触发时this是未定义的,所以我应该如何访问引用的元素this.div以及如果我想要/需要更改状态应该怎么做?

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.不知道 Typescript,但我猜这与使用类似的 ES2015 语法创建组件是一样的,这需要一个构造函数和函数绑定来引用 this.onWheel 工作。

So in ES2015,所以在 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:如果您不想在构造函数中绑定每个函数,另一种解决方案是使用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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