0

when i change the input value, the event handler onChangeEvt will lose 'this'...

how i can get helloworldComponent instance in event handler?

<!--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')
)
Rick Lee
  • 13
  • 4
  • Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Bergi Feb 19 '16 at 05:05

1 Answers1

1

You need to bind the this variable. There are three ways to do this:

1) Use arrow functions. They implicitly bind to the outer this variable. (My preference.)

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

2) Explicitly use function#bind:

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

3) Bind your methods in the constructor:

constructor(...args) {
    super(...args);
    this.onChangeEvt = this.onChangeEvt.bind(this);
}
David L. Walsh
  • 24,097
  • 10
  • 61
  • 46