【问题标题】:reactjs event handler miss thisreactjs 事件处理程序错过了这个
【发布时间】:2016-02-19 03:49:05
【问题描述】:

当我更改输入值时,事件处理程序 onChangeEvt 将丢失 'this'...

如何在事件处理程序中获取 helloworldComponent 实例?

<!--lang:javascript-->

import * as React from 'react';
import * as ReactDom from 'react-dom';

class HelloWorld extends React.Component{
    onChangeEvt(e){
        console.log(JSON.stringify(this))             //undefined
    }
    render(){
        return(
            <div>
                <input onChange={this.onChangeEvt}/>
            </div>  
        )
    }  
}  
ReactDom.render(
    <HelloWorld/>,
    document.getElementById('app')
)

【问题讨论】:

标签: reactjs ecmascript-6


【解决方案1】:

您需要绑定this 变量。有三种方法可以做到这一点:

1) 使用箭头函数。它们隐式绑定到外部 this 变量。 (我的偏好。)

<input onChange={(event) => this.onChangeEvt(event)} />

2) 显式使用function#bind:

<input onChange={this.onChangeEvt.bind(this)} />

3) 在构造函数中绑定你的方法:

constructor(...args) {
    super(...args);
    this.onChangeEvt = this.onChangeEvt.bind(this);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多