You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript日期时间组件报错:Date无构造签名

问题原因

你把React组件命名为Date,直接覆盖了JavaScript全局的Date构造函数。当你在组件内部调用new Date()时,实际上是在尝试实例化自己定义的React函数组件(它没有构造签名),因此TypeScript抛出了构造签名缺失的错误。

解决方案

1. 重命名组件

将组件名改成和全局Date不冲突的名称,比如DateTimeBanner,彻底避免命名冲突。

2. 修复定时器时间不更新的问题

原代码里dateTime是组件挂载时创建的固定日期对象,定时器里重复调用它的toLocaleTimeString()会导致时间无法实时刷新,需要每次都创建新的Date实例获取当前时间。

修改后的完整代码:

import React, { useEffect, useState } from 'react'
import banner from "../assets/banner.png"
import Image from 'next/image'

const DateTimeBanner = (): JSX.Element => {
    // 初始化时获取当前完整日期时间
    const [clock, setClock] = useState<string>(new Date().toLocaleString());

    useEffect(() => {
        const intervalId = setInterval(() => {
            // 每次定时器触发都创建新的Date实例
            const now = new Date();
            setClock(`${now.toLocaleDateString(undefined, {
                weekday: "long",
                year: "numeric",
                month: "long",
                day: "numeric",
            })} ${now.toLocaleTimeString()}`);
        }, 1000);

        // 组件卸载时清除定时器
        return () => clearInterval(intervalId);
    }, []);

    return (
        <div className='w-full relative mb-3'>
            <Image
                className='rounded-xl w-full mx-auto'
                src={banner}
                alt="banner"
                width={700}
                height={240}
            />
            <div className='absolute rounded-xl w-full flex items-center h-full p-4 top-0 left-0'>
                <div className='ml-0 sm:ml-3'>
                    <h1 className='text-3xl md:text-4xl lg:text-6xl text-white font-bold'>
                        {new Date().toLocaleDateString(undefined, {
                            weekday: "long",
                            year: "numeric",
                            month: "long",
                            day: "numeric",
                        })}
                    </h1>
                    <p className='sm:text-xl mt-3 text-white font-bold'>{clock}</p>
                </div>
            </div>
        </div>
    )
}

export default DateTimeBanner

额外提示

  • 永远不要用JavaScript内置对象/函数名作为组件名,比如Date、String、Number等,这类命名冲突会引发难以排查的错误。
  • 定时器中必须每次获取新的Date实例,才能保证时间实时更新,否则会一直停留在组件挂载时的时间点。

内容的提问来源于stack exchange,提问作者Md Habibur Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:15:51