1 说明
1.1 需求说明
在某个运维的前端项目中,首页想展示当前时间,而且模仿百度上的北京时间,有底色,而且动态展示
1.2 相关技术
使用到了如下内容
- React17
- 函数式组件
- Hooks
- Antd
博主学习React不久 用到的js方法或者css样式可能不是最优的 如果有需要改进的地方欢迎指出
2 具体实现
2.1 实际效果
如下是模仿的效果 由于没找到那个时钟 所以只展示了时间和日期
2.2 代码实现
核心代码如下
import React, { useEffect, useRef, useState } from 'react'
import { Card } from 'antd';
import './Home.css'
export default function Home() {
const timmer = useRef()
const [Hour, setHour] = useState('');
const [Seconds, setSeconds] = useState('');
const [Minutes, setMinutes] = useState('');
const [Year, setYear] = useState('');
const [Month, setMonth] = useState('');
const [Day, setDay] = useState('');
const [Weekday, setWeekday] = useState('')
const weekdayMap = {
1: '一',
2: '二',
3: '三',
4: '四',
5: '五',
6: '六',
7: '日'
}
const getNewDate = () => {
const time = new Date();
const year = time.getFullYear();
const month = time.getMonth() + 1;
const day = time.getDate();
const wday = time.getDay()
const hour = time.getHours();
const minutes = time.getMinutes();
const s = time.getSeconds();
const seconds = s <= 9 ? "0" + s : s;
// const t = `${year}年${month}月${day}日 ${hour}:${minutes}:${seconds}`
setHour(hour)
setSeconds(seconds)
if (minutes < 10) {
setMinutes(`0${minutes}`)
} else {
setMinutes(minutes)
}
setYear(year)
setMonth(month)
setDay(day)
setWeekday(weekdayMap[wday])
}
useEffect(() => {
timmer.current = setInterval(getNewDate, 1000);
return () => {
clearTimeout(timmer.current)
}
// eslint-disable-next-line
}, [])
return (
<div className="site-card-wrapper">
<Card title="当前时间" bordered={false}>
<div className="clockclass">
<span className='hourclass'>
<span>{Hour}</span>
{Hour && <span style={{ margin: '0 2px' }}>{':'}</span>}
<span>{Minutes}</span>
</span>
<span className='secondsclass'>
{Seconds}
</span>
<div className='dateclass'>
{Weekday && <p style={{ fontSize: 20, marginBottom: 5, fontWeight: 'bold' }}>
{`星期${Weekday}`}
</p>}
{Month && <p style={{ fontSize: 15, fontWeight: 'bold' }}>
{`${Year}年${Month}月${Day}日`}
</p>}
</div>
</div>
</Card>
</div>
)
}
用到的css样式如下
.clockclass {
width: '400px';
height: '100px';
background-image: linear-gradient(#005fb2,#58a2d9);
border-radius: 16px;
}
.hourclass {
line-height: 100px;
font-size: 55px;
color: white;
font: Arial,sans-serif;
margin-left: 20px;
}
.secondsclass {
font-size: 30px;
color: white;
margin-left: 6px;
font: Arial,sans-serif;
}
.dateclass {
color: white;
margin: 0 15px;
float: right;
margin-top: 20px;
margin-right: 70px;
}
.lunbo {
font-size: 55px;
color: white;
}