React实现时钟效果
本文原创地址链接:http://blog.csdn.net/zhou_xiao_cheng/article/details/52425606,未经博主允许不得转载。
嗯,我又来了,这次的Demo是一个魔力小时钟,永不停歇的小时钟(此处省略N声嘀嗒嘀嗒),用来实时显示当前的时间,哇哈哈~~~
思考
日常生活中看到的时钟通常都是由时针、分针、秒针组成,这三根针不停地转动,用以显示当前的时间,那么站在一只程序猿的角度,每根针究竟是如何转动起来的?又是以什么角度在转动?
我一直认为,学习的过程中,思考是很重要的,它能够让你更好、更快地去理解,以及实现一个功能,这也正是为什么我的文章里几乎都会出现类似:实现思路、思考等这一类词语的原因。
好了,废话少说。首先,我们可以先做出一根针:
class ClockDemo extends React.Component {
render(){
return(
<div className="style">
<div className="clockHourLine"></div>
</div>
)
}
}
ReactDOM.render(<ClockDemo />, document.getElementById('app'))
.style { display: flex; width: 100vw; height: 100vh; align-items: center; justify-content: center; }
.clockHourLine { width: 4px; height: 65px; background-color: black; }
效果图如下:
嗯,很简单,再往CSS里加个偏移角度:transform: rotateZ(45deg);
接下来,让它转起来:
class ClockDemo extends React.Component {
constructor() {
super();
this.state = {
rotateDegree: 0
}
}
componentWillMount() {
setInterval((function() {
this.setState({
rotateDegree: this.state.rotateDegree + 10
})
}).bind(this), 1000)
}
render() {
return (
<div className="style">
<div className="clockHourLine" style={
{transform: 'rotateZ(' + this.state.rotateDegree + 'deg)'}}></div>
</div>
)
}
}
ReactDOM.render(<ClockDemo />, document.getElementById('app'))
以上,就是一根针简单的转动原理。我们通过CSS中的transform属性让我们的元素(针)进行旋转(rotate)操作,此时,可以看到,该针是以其中心点作为原点进行旋转的,再通过修改transform-origin属性的值,便可以更改这根针变形的原点了(不了解这两个属性的,可以戳这里transform与transform-origin的用法)。
上代码:
class ClockDemo extends React.Component {
constructor() {
super()
//随着时间的变化,三根针是不断发生变化的,可以把它们放在this.state中
this.state = {
hour: 0,
minute: 0,
second: 0
}
}
//componentWillMount()是React组件的生命周期函数
componentWillMount() {
var func = function() {
//获取当前时间
var date = new Date()
var minutes = date.getMinutes()
var seconds = date.getSeconds()
//计算旋转角度,并实时改变this.state的值
this.setState({
hour: (date.getHours()) % 12 * (360 / 12) + (360 / 12) * (minutes / 60),
minute: minutes * (360 / 60) + (360 / 60) * (seconds / 60),
second: seconds * (360 / 60)
})
}.bind(this)
func()
//每间隔1s执行一次func()方法
setInterval(func, 1000)
}
render() {
return (
<div className="style">
<img className="backgroundImg" src="http://www.imagebon.com/postpic/2015/11/clock-face_104541.jpg" />
<div className="container">
<div className="clockMinuteLine" style={
{transform: 'rotateZ('+this.state.minute+'deg)'}}></div>
<div className="clockHourLine" style={
{transform: 'rotateZ('+this.state.hour+'deg)'}}></div>
<div className="clockSecondLine" style={
{transform: 'rotateZ('+this.state.second+'deg)'}}></div>
</div>
</div>
)
}
}
ReactDOM.render(<ClockDemo />, document.getElementById('app'))
还可以写得更优雅一点:
height=”512” scrolling=”no” src=”//codepen.io/zhouxiaocheng/embed/LRYOZA/?height=512&theme-id=0&default-tab=js,result&embed-version=2” allowfullscreen=”true” width=”100%;’”>
还没有评论,来说两句吧...