【问题标题】:React Cant Access Class Scope on Event Handler [duplicate]React Cant Access Class Scope on Event Handler [重复]
【发布时间】:2017-12-15 23:16:21
【问题描述】:

我正在尝试创建一个作为文本输入的反应组件。当有人按下回车键时,它必须调用 myMethod()。但是在handleKeyPress 中,我无法访问类范围。我该如何解决这个问题?

class MyContainer extends Component {
    constructor(props, context) {
        super(props, context);        
    }

   myMethod(){}


    handleKeyPress(target) {
        var self = this;
        if(target.charCode === 13) {
            this.myMethod();
        }
    }

    render() {
        <input onKeyPress={this.handleKeyPress}  ref={(input) => this.inputMax = input} type="text" />
    }
}

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您需要绑定处理程序。

class MyContainer extends Component {
    constructor(props, context) {
        super(props, context);
        this.handleKeyPress = this.handleKeyPress.bind(this);
    }

   myMethod(){}


    handleKeyPress(target) {
        var self = this;
        if(target.charCode === 13) {
            this.myMethod();
        }
    }

    render() {
        <input onKeyPress={this.handleKeyPress}  ref={(input) => this.inputMax = input} type="text" />
    }
}

另一种解决方案是使用箭头函数(有性能缺陷)或@autobind decorator

【讨论】:

    【解决方案2】:

    你需要在构造函数中绑定函数。

    constructor(props, context) {
        super(props, context);
        this.handleKeyPress = this.handleKeyPress.bind(this)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2017-06-23
      • 2011-07-07
      • 1970-01-01
      相关资源
      最近更新 更多