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?