我最近开始学习React Native,我很难理解“this”关键字的作用。我知道它在Java中是如何工作的,但在这里似乎有所不同。如果有人能为我说清楚,我会非常感激。示例代码:
import React, { Component } from 'react'
import { Text, View } from 'react-native'
class Home extends Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.'
}
updateState = () ⇒ this.setState({ myState: 'The state is updated' })
render() {
return (
<View>
<Text onPress = {this.updateState}>
{this.state.myState}
</Text>
</View>
);
}
}
export default Home;
答案 0 :(得分:0)
您需要将updateState函数绑定到render函数中的上下文。您还可以定义updateState函数清理程序。
请注意.bind(this)
;
import React, { Component } from 'react'
import { Text, View } from 'react-native'
class Home extends Component {
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.'
}
updateState() {
this.setState({ myState: 'The state is updated' })
}
render() {
return (
<View>
<Text onPress = {this.updateState.bind(this)}>
{this.state.myState}
</Text>
</View>
);
}
}
export default Home;
更多信息here
答案 1 :(得分:0)