当前位置:首页 > React

使用react实现时钟

2026-01-27 10:35:50React

使用react实现时钟

使用 React 实现时钟

方法一:使用 useState 和 useEffect 实现动态时钟

import React, { useState, useEffect } from 'react';

function Clock() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => {
      setTime(new Date());
    }, 1000);

    return () => {
      clearInterval(timerID);
    };
  }, []);

  return (
    <div>
      <h1>当前时间:</h1>
      <h2>{time.toLocaleTimeString()}</h2>
    </div>
  );
}

export default Clock;

方法二:使用类组件实现时钟

import React from 'react';

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      time: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>当前时间:</h1>
        <h2>{this.state.time.toLocaleTimeString()}</h2>
      </div>
    );
  }
}

export default Clock;

方法三:自定义格式显示时间

function formatTime(date) {
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();
  return `${hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
}

// 在以上任一组件中使用
function Clock() {
  // ...
  return (
    <div>
      <h1>自定义格式时间:</h1>
      <h2>{formatTime(time)}</h2>
    </div>
  );
}

方法四:添加日期显示

function Clock() {
  // ...
  return (
    <div>
      <h1>当前日期和时间:</h1>
      <h2>{time.toLocaleDateString()} {time.toLocaleTimeString()}</h2>
    </div>
  );
}

方法五:使用第三方库(如 moment.js)

import moment from 'moment';

function Clock() {
  const [time, setTime] = useState(moment());

  useEffect(() => {
    const timerID = setInterval(() => {
      setTime(moment());
    }, 1000);

    return () => clearInterval(timerID);
  }, []);

  return (
    <div>
      <h1>Moment.js 格式:</h1>
      <h2>{time.format('YYYY-MM-DD HH:mm:ss')}</h2>
    </div>
  );
}

使用react实现时钟

标签: 时钟react
分享给朋友:

相关文章

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何diff

react如何diff

React Diff 算法原理 React 的 Diff 算法是 Virtual DOM 的核心部分,用于高效更新真实 DOM。其核心思想是通过对比新旧 Virtual DOM 树的差异,最小化 DO…

如何用react

如何用react

使用React的基本步骤 安装Node.js和npm 确保系统已安装Node.js和npm。Node.js自带npm,可从官网下载安装包。安装完成后,通过命令行验证版本: node -v npm -…

react如何发音

react如何发音

React的发音 React的正确发音为 /riˈækt/,类似于“ree-akt”。以下是详细说明: 发音分解 第一个音节“Ree”发音类似英文单词“see”中的“ee”音。 第二个音节…