1

This style is what I see on tutorials everywhere

  onChangeText = { (e)=>{this.setState({input:e})} }

Another style without lambda expressions

  changeText: function(text) {
    this.setState({input: text});
  },
  render: function() {
    return (
      <React.TextInput onChangeText={ this.changeText } />
    );
  }

However this doesn't.

  render: function() {
    return (
      <React.TextInput onChangeText = { function(text) {this.setState({input: text});} }/>
    );
  }
  1. For code block 2, where does this.changeText get the input text from?
  2. For code block 3, why can't I declare the function inline?

I'm not sure what's the proper terms to look this up, so I appreciate if anybody can point me in the direction

Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
holangun
  • 66
  • 6

1 Answers1

4

There is a difference between ES6 arrow functions and classical functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

text => { /* `this` is capture from the enclosing context */ }

vs

function (text) { /* `this` is set by the caller */ }

in your third code block, I have no idea what this will be, but there is absolutely no way it can be your instance class (because the caller of onChangeText prop don't know you) - so this.setState can't work.

However this should work:

<React.TextInput onChangeText = {
  (function(text) {this.setState({input: text})}).bind(this)
} />

but it's not as efficient as using ES6 arrow function (and not very concise).


Also you must know that the code block 2 only works if using React.createClass(), because all methods are magically auto-bounded to the class instance. If using ES6 Class, you must do something like:

class MyComp extends React.Component {
  changeText = text => {
    this.setState({ ... });
  };
  render () { ... }
}

(using class property will bind to this)

gre
  • 1,841
  • 2
  • 16
  • 26