我希望有人可以在这里为我提供帮助,我环顾四周,无法以我理解的方式找到解决方案,我来自python背景,并且开始重新学习javascript,现在反应为母语,所以当然我正在这样做的教程!就像您可能会想到的那样,我正在跟踪一个使用“ React.createClass()”函数的教程,为了更好地理解我想要的所有内容,请使用“类StopWatchNew扩展组件” ES6方法,对我来说似乎更整洁,更合乎逻辑(让我知道是否有更好的方法,我仍然对此感到困惑)
无论如何,我试图在类中引用我的类方法,就像这样;
static updateTimeState() {
var startTime = new Date();
this.setState({
timeElapsed: new Date() - this.startTime
});
};
handleStartPress() {
this.updateTimeState()
};
运行此行,react-native会抛出此错误
this.updateTimeState()
this.updateTimeState不是函数。 (在
'this.updateTimeState()','this.updateTimeState'未定义)
我很困惑,因为在JSX render方法中引用类方法似乎不是问题。.我知道python与JS有很大不同,但这基本上是我想做的,如果有帮助的话。
class MyClass(object):
def myFunc(self):
pass
self.myFunc()
任何帮助表示赞赏,谢谢!
示例代码:
import React, { Component } from 'react';
import formatTime from 'minutes-seconds-milliseconds'
import {
View,
Text,
TouchableHighlight,
AppRegistry,
StyleSheet
} from 'react-native';
class StopWatchNew extends Component {
// Setting the inital state
constructor(props) {
super(props);
this.state = {timeElapsed: null};
var startTime = new Date();
}
border(color) {
return (
{
borderColor: color,
borderWidth: 4
}
)
};
startStopButton() {
return (
<TouchableHighlight
underlayColor="grey"
onPress={this.handleStartPress}>
<Text>
Start
</Text>
</TouchableHighlight>
)
};
lapButton() {
return (
<View>
<Text>
Lap
</Text>
</View>
)
};
static updateTimeState() {
var startTime = new Date();
this.setState({
timeElapsed: new Date() - this.startTime
});
};
handleStartPress() {
this.updateTimeState()
};
render() {
return (
<View style={styles.container}>
<View style={styles.statusBar}></View>
<View style={[styles.header, this.border('yellow')]}>
<View style={[this.border('red'), styles.timerWrapper]}>
<Text>{this.state.timeElapsed}</Text>
</View>
<View style={[this.border('green'), styles.buttonWrapper]}>
{this.startStopButton()}
{this.lapButton()}
</View>
</View>
<View style={[styles.footer, this.border('blue')]}>
<Text>
I am lap
</Text>
</View>
</View>
)
};
}
var styles = StyleSheet.create({
statusBar: {
flex:0.08,
},
container: {
flex: 1,
alignItems: 'stretch'
},
header: { // Yellow
flex: 1
},
footer: { // Blue
flex: 1
},
timerWrapper: { // Red
flex: 5,
justifyContent: 'center',
alignItems: 'center'
},
buttonWrapper: { // Green
flex: 3,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center'
}
})
export default StopWatchNew;
最佳答案
您正在使用this.handleStartPress
作为事件处理程序的回调。由于react ES6不会自动绑定回调,因此在事件处理程序的上下文中调用this.handleStartPress
,并且this
并不引用StopWatchNew
类实例。
在构造函数中手动将this.handleStartPress
绑定到类实例的this
:
constructor(props) {
super(props);
this.state = {timeElapsed: null};
var startTime = new Date();
this.handleStartPress = this.handleStartPress.bind(this);
}