I'm trying to get my head around the scope of functions. _internalFunction
works well, but how do I call _externalFunction
instead?
I've tried self=this
and then this._externalFunction
inside _renderRow and also tried () => {this._externalFunction}
but it didn't work.
class sandbox extends Component {
//some code removed for clarity
_renderRow(item) {
const _internalFunction = () => {
Alert.alert('Internal');
};
return (<Text onPress={_internalFunction}>{item}</Text>);
}
_externalFunction() {
Alert.alert('External');
};
}
Here's the code in React Native Playground to fiddle with: https://rnplay.org/apps/5CIGvA
Thanks in advance! :)
In ES6 you need to manually bind this
to the instance. Here is a quote from React documentation :
In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don't automatically bind
this
to the instance. You'll have to explicitly use.bind(this)
in the constructor:
Therefore you need to bind your function in constructor:
constructor() {
super();
this._externalFunction = this._externalFunction.bind(this);
}
And then you can use this._externalFunction
in your component:
_renderRow(item) {
return (<Text onPress={this._externalFunction}>{item}</Text>);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.