I am trying to understand how this works in React Native. When I use this.f() it throws and error, but when I just use f(), it doesn't. I am not sure why.
import React, { Component } from 'react'
import {StyleSheet, Text, View } from 'react-native'
class Home extends Component {
state = {
myState: 'a'
}
updateState = () => this.setState({ myState: 'The state is updated' })
render() {
a = 37;
function f() {
return this.a;
}
//var f = this.f;
return (
<View style = {styles.container}>
<Text onPress = {this.updateState}>
{this.state.myState}
</Text>
<Text> {this.f()} </Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingHorizontal: 30,
paddingVertical: 30,
alignItems: 'center'
}
})
export default Home;
The this
keyword in your render()
function is a reference to the Home
instance. Home
's prototype
has no property f
so it throws an error cause you're trying to invoke undefined
.
The function f()
you declared is scoped inside the render()
function (which is definitely a bad thing to do, but that's a different topic), and this
will be bound to the global context, or to undefined, if in strict mode. More here .
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.