1
class HelloWorldComponent extends React.Component {
  constructor() {
    super()
    this.getInput = this.getInput.bind(this)
  }
  getInput() {
    alert('focused');
  }
  render() {
    return (      
      <input type="text" onFocus={getInput}/>    
    );
  }
}

ReactDOM.render(
  <HelloWorldComponent/>,
  document.getElementById('react_example')
);

What's wrong with this code? can't get the alert to fire, I got getInput is not defined error.

http://jsbin.com/qoduyawaci/1/edit

4
  • 1
    this.getInput = this.getInput.bind(this) - why? Commented Jan 20, 2017 at 4:21
  • @JaromandaX why not? Commented Jan 20, 2017 at 5:45
  • Look, I may be wrong, but I would've thought that this.getInput doesn't need to be bound to this because it already is a property of this ... I'll admit that I can only say I'm 99% sure of how this works, but it just looks like odd (redundant) code to me Commented Jan 20, 2017 at 5:47
  • @JaromandaX it's needed because I use es6 syntax, try here jsbin.com/qozupufoja/1/edit?html,js,console,output with the code you think that should work. Commented Jan 20, 2017 at 5:59

3 Answers 3

4

You forgot to add the correct refference. use this.getInput instead of getInput.

like this

class HelloWorldComponent extends React.Component {
  constructor() {
    super()
    this.getInput = this.getInput.bind(this);
  }
  getInput() {
    alert('focused');
  }
  render() {
    return (      
      <input type="text" onFocus={this.getInput}/>    
    );
  }
}

ReactDOM.render(
  <HelloWorldComponent/>,
  document.getElementById('react_example')
);
Sign up to request clarification or add additional context in comments.

Comments

1

You should use this.getInput instead of getInput

http://jsbin.com/nehadisuvu/1/edit?html,js,output

Comments

0

Use this.getInput to call the function. Also you can use arrow functions in ES6 to avoid binding.

getInput = () => {
    alert('focused');
 }

and you can avoid

this.getInput = this.getInput.bind(this)

in constructor. This is the correct ES6 method.

http://jsbin.com/sebotirito/1/edit?html,js,output

3 Comments

Your first suggestion is not valid ES6. It's an experimental feature that requires additional configuration to work.
@FelixKling this.getInput is used for accessing class member function.
I never disputed that. Maybe I didn't express myself clearly. I was talking about getInput = () => ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.