• “黑神话·悟空”免安装在线玩,无视显卡等硬件要求!!
  • √ 游戏免下载安装 √ 5分钟随开随玩 √ 关机不计费!低至¥14.90/月!
🔥进入竞技-直面天命🔥

React Hooks+ TypeScript 实现24小时的倒计时并支持响应式布局:768以上按1440样式展示,768及其以下按768样式展示

时间2023-03-21 17:20:58 提问来自 北京市北京市 的网友 分类创作 浏览739
```jsx import React, { useState, useEffect } from 'react' import { render } from 'react-dom' import styled from 'styled-components' // 响应式样式,当尺寸大于768px时,按1440px的样式展示;当尺寸小于768px时,按768px的样式展示。 const CountDownWrapper = styled.div<{ isBig: boolean }>` width: ${props => (props.isBig ? 1440 : 768)}px; .countdown-item{ // 样式省略...} @media screen and (max-width: 768px) { // 当屏幕宽度小于768时重写样式 width: 768px; .countdown-item{ // 样式省略...} } `; interface IProps { // 定义一个参数接口IProps endTime?: string | number; // 结束时间(可选参数) isBig?: boolean; // 是否是大屏幕(默认false) } const CountDown = (props: IProps) => { const [endTime] = useState(() => new Date(props.endTime).getTime()); const [nowTime, setNowTime] = useState(Date.now()); const [difference, setDifference] = useState<number>(0); const [isBig] = useState<boolean>(props.isBig || false); let timerId: any; // 计时器ID /** * @description 计算差值 */ const getDifferenceValue = () => { let differenceValue = endTime - nowTime; if (differenceValue > 0) setDifference(differenceValue); else clearInterval(timerId); }; /** * @description 运行计时函数 */ const runTimerFunc = () => { timerId && clearInterval(timerId); timerId = setInterval(() => { setNowTime((prevNowtime) => prevNowtime + 1000); }, 1000); }; /** * @description 运行所有函数 */ useEffect(() => { getDifferenceValue(); runTimerFunc(); return () => clearInterval(timerId); }, [] ); return ( <CountDownWrapper isBig={isBig}> <div className="countdown-item"> <span className="num">{Math.floor((difference % 86400000) / 3600000)}</span> <span className="text">时</span> </div> <div className="countdown-item"> <span className="num">{Math.floor((difference % 3600000) / 60000)}</span> <span className="text">分</span> </div> <div className="countdown-item"> <span className="num">{Math.floor((difference % 60000) / 1000)}</span> <span className="text">秒</span> </div></CountDownWrapper>)}; render (<CountDown endTime={new Date('2020/12/31 23:59')} />, document.getElementById('root') ) ;

点击这里,进行内容创作

创作工场 免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!

上一篇 我是一个可爱胖胖的女孩,离过1次婚因为对方出轨,我很聪明但是情感上很单纯,我适合什么样的伴侣 下一篇 改善自我心态后的所需资源