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

React应用目录选择对话框实现遇编译错误,求解决方案

解决React中目录选择对话框的TypeScript编译错误

我刚踩过一模一样的坑!在React里想实现目录选择对话框,用<input type="file" directory webkitdirectory />的时候,TypeScript直接报错:Property 'directory' does not exist on type 'DetailedHTMLProps<InputHTMLAttributes, HTMLInputElement>',哪怕升级到React 17.rc.1也没搞定。

后来在评论区看到@Scratch'N'Purr分享的临时解决方案,亲测有效,分享给你:

只需要在项目的TypeScript类型定义文件里(比如react-app-env.d.ts,没有的话新建一个custom-react-types.d.ts就行)添加这段扩展代码:

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // 给React的HTMLAttributes补上目录选择相关属性
    directory?: string;
    webkitdirectory?: string;
  }
}

原理其实很简单:React官方的TypeScript类型定义还没跟上浏览器的支持,没有包含directory和webkitdirectory这两个属性,我们通过模块扩展的方式手动把这些属性加到类型里,TypeScript就不会再报错啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 07:47:39