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

React自定义Hook中能否返回div元素?遇TS报错求解决方案

解决Cannot find name 'div'.ts(2304)错误的方案

针对你在自定义Hook中返回JSX元素时出现的这个错误,以下是几个直接的解决方向:

  • 检查文件扩展名
    确保你的自定义Hook文件后缀是.tsx,而不是.ts。TypeScript只会在.tsx文件中解析JSX语法,.ts文件里写<div>这类标签会被当作未定义的变量处理,从而触发该错误。

  • 修正tsconfig.json配置
    打开项目根目录的tsconfig.json,确认以下配置项:

    • jsx字段设置为react-jsx(React 17及以上版本推荐)或react;
    • include数组包含你的Hook文件所在的目录,比如"src/**/*",确保配置能覆盖到目标文件。
      示例配置片段:
    {
      "compilerOptions": {
        "jsx": "react-jsx",
        // 其他配置...
      },
      "include": ["src/**/*"]
    }
    
  • 完善IColumn类型定义
    确认IColumn接口中onRender方法的返回值类型正确,应该指定为React.ReactNode或JSX.Element,这样TypeScript才能识别返回的JSX元素。示例:

    import type { ReactNode } from 'react';
    
    interface IColumn {
      key: string;
      onRender: (item: IDocumentItem) => ReactNode;
      data: string;
    }
    

内容的提问来源于stack exchange,提问作者Ozan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:10:40