reactjs - Typescript上传目录,类型上不存在属性 'directory'

标签 reactjs typescript

我有一个基本的文件输入,我想允许用户上传整个目录

      <input
        type='file'
        directory=''
        webkitdirectory=''
        className={cssClass}
        onChange={processFiles}
      />

这给出了 typescript 错误

Type '{ type: "file"; directory: string; webkitdirectory: string; className: string; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
  Property 'directory' does not exist on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.ts(2322)

最佳答案

截至今天,React 提供的当前类型似乎还没有一种“原生”方法可以做到这一点。您可以在 React 的存储库上查看 this issue。最好的方法似乎是自己声明这些类型:

declare module 'react' {
  interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
    // extends React's HTMLAttributes
    directory?: string;
    webkitdirectory?: string;
  }
}

根据问题上的this comment

这个类型定义只会让 Typescript 感到冷淡,但请记住,React 会将它无法识别的 props 转发给底层 DOM 元素(又名 <input /> ),即使 React 不知道这一点( checkout this blog post on React's website ),也可以使这项工作正常进行。

关于reactjs - Typescript上传目录,类型上不存在属性 'directory',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72787050/

相关文章:

reactjs - React 路由器更改 url 而不重新加载页面

javascript - 使用 Material-UI 创建导航栏

reactjs - react 改变点击时列表项的类别

java - 在构建单页应用程序(大规模)时,我应该使用 webpack 还是只使用 html 导入

typescript - noImplicitAny 不适用于通用高阶函数

reactjs - 如果用户已经在重定向页面上,history.push 会进行额外的重定向,并忽略搜索参数

typescript - 为什么映射类型中与可区分联合的交集会给出所有类型的联合而不是缩小它?

typescript - 你如何从 typescript AST 中获得推断类型?

typescript - 是否可以从 TypeScript 中的字符串文字数组定义联合类型别名?

javascript - 将变量传递给在循环中调用的异步 JavaScript 函数 (React)