我正在尝试创建一个呈现滴答作响的时钟的 react 组件。我正在为不同的时区使用 moment 和 moment-timezone 。我能够创建一个带有静态时钟(不递增)的组件,但我无法创建一个滴答作响的时钟。代码如下:
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import moment from 'moment';
import 'moment-timezone';
export default class TimeClock extends React.Component {
constructor(props) {
super(props);
this.state = { time: moment().clone().tz(this.props.timezone).toLocaleString() };
this.displayTime = this.displayTime.bind(this);
}
displayTime(){
//let now = moment();
//let location = now.clone().tz(this.props.timezone);
this.setState({
time: moment().clone().tz(this.props.timezone).toLocaleString()
});
//return location.toLocaleString();
}
render(){
//let now = moment();
//let location = now.clone().tz(this.props.timezone);
//let timezone = this.props.timezone;
return (
<div>
<p>{this.props.timezone}</p>
<p>{setInterval(this.displayTime,1000)}</p>
</div>
);
}
}
注意:它从父组件 App.js 传递一个 prop(时区)。
当前代码输出如下:
Australia/Melbourne
#######
其中 ####### 表示从 5 或 6 开始并迅速增加的某个数字。
有人可以解释我做错了什么吗?
编辑:发布此问题后不久,我找到了以下链接 ( Where to apply my moment() function in a react component? ),我将其改编为我的代码并使其正常工作,但我不明白为什么我的尝试没有奏效。我是新手。
最佳答案
您的代码不会呈现与当前时间相关的任何内容。这一行:
<p>{setInterval(this.displayTime,1000)}</p>
不打印当前时间 - 它显示创建的时间间隔的 ID,因为这是 setInterval()
函数返回的内容。
因此,首先,您应该根据组件的状态更改此行以显示时间。这可以像这样完成:
<p>{this.state.time}</p>
您必须做的另一件事是正确创建间隔。在 render()
方法中设置它不是一个好主意,因为您将创建一个新的间隔
componentDidMount() {
// Arrow function allows you to use "this" in context of the Component
this.interval = setInterval(() => {
this.displayTime();
}), 1000);
}
(您还应该记得在组件从 View 中移除后停用间隔)。
关于javascript - 在 React 中使用 moment & moment-timezone 创建运行时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601565/