【问题标题】:reactjs typescript event this undefinedreactjs typescript事件这个未定义
【发布时间】:2016-03-19 19:49:41
【问题描述】:

我得到了以下用 typescript 编写的组件。 (来自 absolutetyped.org 的类型定义)。我将 onWheel 事件绑定到一个函数。但是当它被触发时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 >)
    }
}

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    不了解 Typescript,但我猜这与使用类似 ES2015 语法创建组件时需要构造函数和函数绑定以引用 this.onWheel 工作时相同。

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

    【讨论】:

    • 这实际上是将 React 组件中的事件处理程序绑定到 Qwertiy 答案的首选方式。如果你像上面的 sn-p 那样在构造函数内部进行绑定,这意味着你只创建一次函数的副本,而如果你在 render 方法内进行绑定,则每次 React re 时都会重新创建函数-渲染组件。当性能是主要考虑因素时,请牢记这一点。
    • 那么事件是如何绑定的呢?我还是得把 onWheel={this.onWheel} 放在 render 方法中吧?
    • 按照你已经做的方式去做。它应该可以正常工作。我的代码示例没有onWheel(e: React.WheelEvent),因为关键是构造函数中发生了什么。
    【解决方案2】:

    如果您不想在构造函数中绑定每个函数,另一种解决方案是使用 lambda:

    class foo extends React.Component {
      constructor(props) {
        super(props);
      }
    
      // The lambda creates a lexical scope so it's autobound
      onWheel = () => {
        ....
      }
    
      render () {
        ....
      }
    }
    

    您可以阅读更多here

    【讨论】:

    • 打我一拳。
    【解决方案3】:
    onWheel= { this.onWheel}
    
    onWheel={this.onWheel.bind(this)}
    

    【讨论】:

    • 你也可以写成lambda形式onWheel={e =&gt; this.onWheel(e)}它会使用闭包调用相应的方法
    【解决方案4】:

    简单的事情是将其转换为自动绑定的箭头函数:

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

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2016-09-01
      • 2016-05-22
      • 2015-09-21
      相关资源
      最近更新 更多