[英]React Native - use a state variable in a static function
I'm new to React-Native, i have a problem creating my app. 我是React-Native的新手,我在创建应用程序时遇到问题。 Basically, i have a main application that do things, one of those is setting a Date variable in state called: sleepTime. 基本上,我有一个做事的主应用程序,其中之一是将Date变量设置为状态:sleepTime。 Now i've created a clock that works perfectly and every seconds is updated. 现在,我创建了一个完美运行的时钟,并且每秒钟都会更新。 My problem now is to create a function into my main application that compare the actual date (given from the clock) with the date saved before. 我现在的问题是在我的主应用程序中创建一个函数,将实际日期(从时钟中给出)与之前保存的日期进行比较。 The problem is that i've used a static function wich is called on every tick in the clock class, this function (compareTime()) is in the main class and obviusly i get the "undefined is not an object" when I call it. 问题是我使用了一个静态函数,该函数在时钟类的每个刻度上调用,该函数(compareTime())在主类中,当我调用它时,我得到的是“未定义不是对象” 。 What i can't figure out is how to link the call made by clock with the date that i've saved before. 我不知道的是如何将时钟拨打的电话与我之前保存的日期联系起来。
This is the static function: 这是静态函数:
static compareTime(){
const sleepTime = this.state.sleepTime;
if(new Date().toLocaleString() == sleepTime){
this.stopTimer();
}
}
Clock class: 时钟类别:
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>
);
}
}
And the return of the main render wich is the only thing that links main and clock: 而主渲染夹层的返回是唯一链接main和clock的东西:
return (
<View style={styles.container}>
<Clock />
<Text style={styles.greeting}>
Sleep time: {sleepTime}.
</Text>
</View>
)
You can use props for that. 您可以使用道具 。 Since the is a subcomponent of MainApplication, you can pass the function comparetime() to the as props and this function can be called from within the 由于是MainApplication的子组件,因此您可以将函数comparetime()传递给as道具,并且可以从内部调用该函数。
The main render would have, 主要渲染器将具有
<Clock compareTime={this.compareTime.bind(this)}/>
And the Clock class can use the function from props, Clock类可以使用props中的函数,
tick() {
this.setState({
time: new Date().toLocaleString()
});
this.props.compareTime();
}
You can also pass parameters if you want to get values from Clock class to Main. 如果要从Clock类获取值到Main,也可以传递参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.