1

I've been learning about React Native recently and I needed to access a custom component's properties after the component is, e.g. touched. I defined the following component:

export class OperationBox extends React.Component {
  constructor(props) {
    super(props);
  }

  startOperation() {
    Alert.alert("starting operation " + this.props.operation);
  }

  render() {
    return (
      <TouchableHighlight onPress={this.startOperation}>
          <Text>{this.props.operation}</Text>
      </TouchableHighlight>

    );
  }
}

The app crashes when the component is touched saying that undefined is not an object when evaluating this.props.operation. However if I define the function startOperation() like this: startOperation = () => { ... }, I get the expected behaviour.

Now, I thought I understood how these arrow functions worked. Coming from a Swift background, I thought they were just like closures, but surely I'm missing something? Why does the first way not work but the second does?

Youssef Moawad
  • 2,846
  • 5
  • 28
  • 50

2 Answers2

0

Because function is not binded to the class if defined as:

someFunction() { }

And is binded if defined as:

someFunction = () => { }

Another possibility is to explicitly bind it in constructor:

constructor(props) {
    super(props);
    this.someFunction = this.someFunction.bind(this);
}

Difference is that startOperation function is passed as callback, and executed in different environment (outside the initial class), so this is referring to different object.

Bogdan Kuštan
  • 5,427
  • 1
  • 21
  • 30
0

Simple Answer: In ES6 Classes

funcName() {} creates "Class Methods" but funcName = () => {} don't.

It's about all ECMASCRIPT 2015 syntax standards.

However, you can overcome that ;)

Is it possible to use arrow functions in classes with ES6?

solimanware
  • 2,952
  • 4
  • 20
  • 40