0

I am trying to create a react component which is a text input. When someone pressed enter it must call myMethod(). However in handleKeyPress, I can not access class scope. How can I fix this ?

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" />
    }
}
Mehmet Eren Yener
  • 2,006
  • 1
  • 23
  • 37
  • 1
    for that you need to **bind** the `handleKeyPress`, put this line in the constructor: `this.handleKeyPress = this.handleKeyPress.bind(this)` – Mayank Shukla Jul 11 '17 at 18:37
  • 1
    See also: http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html - 6 alternatives listed, choose one :) – jsalonen Jul 11 '17 at 18:38

2 Answers2

1

You need to bind the handler.

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" />
    }
}

Another solution can be to use an arrow function (which has performance drawbacks) or an @autobind decorator

Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133
1

You need to bind the function in the constructor.

constructor(props, context) {
    super(props, context);
    this.handleKeyPress = this.handleKeyPress.bind(this)
}
T4rk1n
  • 1,380
  • 12
  • 15