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" /> } } 
2
  • 1
    for that you need to bind the handleKeyPress, put this line in the constructor: this.handleKeyPress = this.handleKeyPress.bind(this) Commented Jul 11, 2017 at 18:37
  • 1
    See also: egorsmirnov.me/2015/08/16/react-and-es6-part3.html - 6 alternatives listed, choose one :) Commented Jul 11, 2017 at 18:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You need to bind the function in the constructor.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.