当前位置: 首页 > news >正文

react实现实时计时的最简方式

js中时间的处理,不借助于moment/dayjs这样的工具库,原生获取格式化的时间,最简单的实现方式可以参考下面这样。

实现效果请添加图片描述

代码实现

  • 封装hooks
import { useState, useEffect } from "react";export function useCountTime() {const [time, setTime] = useState(new Date());useEffect(() => {const timer = setInterval(() => {setTime(new Date());}, 1000);return () => {clearInterval(timer);};}, []);return formatDate(time);
}function formatDate(date) {return date.toLocaleString("zh-cn", {weekday: "long",year: "numeric",month: "long",day: "numeric",hour: "numeric",minute: "numeric",second: "numeric",});
}
  • 使用
import { useCountTime } from "../../components/TimeCount";...
const time = useCountTime()
return (<><h3>今天是星期 {time}</h3></>
)

鲜为人知的内置时间格式化

function formatDate(date) {return new Intl.DateTimeFormat("zh-CN", {hour: "numeric",minute: "numeric",second: "numeric",hour12: false,weekday: "long",year: "numeric",month: "long",day: "numeric",}).format(date);
}

福利推送

文档参考链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
有兴趣的可以去了解下
在这里插入图片描述

鼠标移动坐标

  • 封装鼠标移动坐标的hooks请添加图片描述
import { useState, useEffect } from "react";export function useMouse() {const [mouse, setMouse] = useState({ x: 0, y: 0 });function handleMouseMove(event) {setMouse({ x: event.clientX, y: event.clientY });}useEffect(() => {window.addEventListener("mousemove", handleMouseMove);return () => {window.removeEventListener("mousemove", handleMouseMove);};}, []);return mouse;
}
import { useMouse } from "../../hooks/userMouse";
const { x, y } = useMouse();
return (<><div>x:{x} y:{y}</div></>
)
http://www.lryc.cn/news/459511.html

相关文章:

  • 时尚的社会心理机制:求同和树异这对互为矛盾的心理动机,使得人们在社会生活中互相模仿、互相追逐、互相竞争,使得时尚的钟摆永不停息。
  • HarmonyOS NEXT应用开发实战(二、封装比UniApp和小程序更简单好用的网络库)
  • [Hbase]一 HBase基础
  • React.createRef(),React.forwardRef(),forwardRef()结合next.js的link进行路由跳转
  • C++从入门到起飞之——AVL树 全方位剖析!
  • 利用Fail2Ban增强Jupyter Notebook安全性以防范目录遍历攻击
  • 智能贴身监测,健康生活建议,圆道妙医智能手表体验
  • C++——AVL树
  • 极市平台 | 无人机相关开源数据集资源汇总
  • React和Vue区别,以及注意事项
  • 光伏项目难管理的问题如何解决?
  • 图片美化SDK解决方案,赋能H5与小程序极致体验
  • Kron Reduction消去法如何操作,矩阵推导过程
  • 实时开放词汇目标检测(论文复现)
  • 陪诊小程序搭建:打造便利的陪诊环境
  • Qt5.15.2静态编译 MinGW with static OpenSSL
  • Linux Ubuntu dbus CAPI ---- #include<dbus.h>出现“无法打开源文件dbus/xxx.h“的问题
  • React01 开发环境搭建
  • 数据结构之旅(顺序表)
  • 掌握 C# 内存管理与垃圾回收机制
  • 【JavaEE】——初始网络原理
  • Nginx和Lua配合使用
  • 程序化交易是什么,它有哪些优势,需要注意什么?
  • 水库抽样算法(大数据算法作业)
  • SHCTF-2024-week1-wp
  • docker-comapose安装部署mysql
  • C语言初阶-数据类型和变量【下】
  • C++:命名空间(namespace)详细介绍与案例
  • 专题十一_递归_回溯_剪枝_综合练习_算法专题详细总结
  • java中Runnable接口是什么?基本概念、工作原理、优点、`Runnable`与`Thread`的对比、与`Callable`接口的对比、实际场景