[英]React Native - use a state variable in a static function
我是React-Native的新手,我在創建應用程序時遇到問題。 基本上,我有一個做事的主應用程序,其中之一是將Date變量設置為狀態:sleepTime。 現在,我創建了一個完美運行的時鍾,並且每秒鍾都會更新。 我現在的問題是在我的主應用程序中創建一個函數,將實際日期(從時鍾中給出)與之前保存的日期進行比較。 問題是我使用了一個靜態函數,該函數在時鍾類的每個刻度上調用,該函數(compareTime())在主類中,當我調用它時,我得到的是“未定義不是對象” 。 我不知道的是如何將時鍾撥打的電話與我之前保存的日期聯系起來。
這是靜態函數:
static compareTime(){
const sleepTime = this.state.sleepTime;
if(new Date().toLocaleString() == sleepTime){
this.stopTimer();
}
}
時鍾類別:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleString()
};
}
componentDidMount() {
this.intervalID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
tick() {
this.setState({
time: new Date().toLocaleString()
});
MainPage.compareTime();
}
render() {
return (
<Text style={styles.greeting}>
The time is: {this.state.time}
</Text>
);
}
}
而主渲染夾層的返回是唯一鏈接main和clock的東西:
return (
<View style={styles.container}>
<Clock />
<Text style={styles.greeting}>
Sleep time: {sleepTime}.
</Text>
</View>
)
您可以使用道具 。 由於是MainApplication的子組件,因此您可以將函數comparetime()傳遞給as道具,並且可以從內部調用該函數。
主要渲染器將具有
<Clock compareTime={this.compareTime.bind(this)}/>
Clock類可以使用props中的函數,
tick() {
this.setState({
time: new Date().toLocaleString()
});
this.props.compareTime();
}
如果要從Clock類獲取值到Main,也可以傳遞參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.