【发布时间】:2018-01-17 23:39:49
【问题描述】:
我正在尝试创建一个呈现滴答时钟的反应组件。我正在为不同的时区使用时刻和时刻时区。我能够创建一个带有静态时钟(不增加)的组件,但我无法创建一个滴答作响的时钟。代码如下:
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?),我将其改编为我的代码并使其工作,但我不明白为什么我的尝试没有工作。我是新手。
【问题讨论】:
-
WRT 时刻,使用
format,而不是toLocaleString,而且你不需要在本地时间克隆或获取。moment.tz(thetimezone).format(yourdesiredformat)会起作用。 -
是的,我应该删除带有“now”和“location”变量的代码,因为我没有使用它们。我将编辑上面的代码。
标签: javascript reactjs meteor momentjs