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

NextJS+TS项目中UploadCare组件JSX类型错误求助

解决Next.js + TypeScript中UploadCare自定义元素类型报错问题

问题原因

UploadCare的uc-*组件属于Web自定义元素,TypeScript默认不会识别这些非标准JSX标签,因此需要手动扩展JSX全局类型。

解决方案步骤

1. 修正自定义类型声明文件

将你的custom-elements.d.ts修改为以下内容,确保类型声明在全局命名空间中,并且以模块形式导出:

declare global {
  namespace JSX {
    interface IntrinsicElements {
      'uc-config': {
        ctxName?: string;
        pubkey?: string;
        [key: string]: any; // 兼容未声明的额外属性
      };
      'uc-file-uploader-regular': {
        ctxName?: string;
        cssSrc?: string;
        [key: string]: any;
      };
      'uc-upload-ctx-provider': {
        ctxName?: string;
        ref?: React.Ref<any>;
        [key: string]: any;
      };
    }
  }
}

export {};

说明:添加declare global确保类型被全局识别,export {}将文件标记为模块,避免TypeScript类型合并冲突。

2. 确认TypeScript配置包含类型文件

检查tsconfig.json的include数组,确保包含你的自定义类型文件:

{
  "compilerOptions": {
    // 其他配置...
  },
  "include": [
    "custom-elements.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts"
  ]
}

修改后重启VSCode的TypeScript服务(快捷键:Ctrl+Shift+P,选择TypeScript: Restart TS Server),让配置生效。

3. 调整组件内初始化逻辑

将UC.defineComponents(UC)移到useEffect中,确保仅在客户端执行,并完善类型与清理逻辑:

'use client'
import React, { useEffect, useRef } from 'react'
import * as UC from '@uploadcare/file-uploader';
import { useRouter } from 'next/navigation'
import type { UploadCtxProvider } from '@uploadcare/file-uploader';

type Props = {
  onUpload: (e: string) => any
}

const UploadCareButton = ({ onUpload }: Props) => {
  const router = useRouter()
  const ctxProviderRef = useRef<UploadCtxProvider>(null)

  useEffect(() => { 
    // 仅在客户端初始化UploadCare组件
    UC.defineComponents(UC);
    
    const handleUpload = async (e: any) => {
      const file = await onUpload(e.detail.cdnUrl)
      if (file) {
        router.refresh()
      }
    }
    ctxProviderRef.current?.addEventListener('file-upload-success', handleUpload)

    // 清理事件监听,避免内存泄漏
    return () => {
      ctxProviderRef.current?.removeEventListener('file-upload-success', handleUpload)
    }
  }, [onUpload, router])

  return (
    <div>
      <uc-config
        ctx-name="my-uploader"
        pubkey="a9428ff5ff90ae7a64eb"
      />

      <uc-file-uploader-regular
        ctx-name="my-uploader"
        css-src={`https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.35.2/web/lr-file-uploader-regular.min.css`}
      />

      <uc-upload-ctx-provider
        ctx-name="my-uploader"
        ref={ctxProviderRef}
      />
    </div>
  )
}

export default UploadCareButton

说明:细化了ctxProviderRef的类型替代any,提升类型安全性;同时添加事件清理逻辑,避免内存泄漏。

4. 验证解决方案

完成上述修改后,重新编译项目,VSCode的类型报错应该会消失。如果仍有问题,可以尝试:

  • 删除.next文件夹后重新构建
  • 确保@uploadcare/file-uploader包的版本与官方文档一致

内容的提问来源于stack exchange,提问作者k4cper-g

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 09:27:01