Bil*_*ill 2 typescript reactjs
我有一个基本的文件输入,我想允许用户上传整个目录
<input
type='file'
directory=''
webkitdirectory=''
className={cssClass}
onChange={processFiles}
/>
Run Code Online (Sandbox Code Playgroud)
这给出了打字稿错误
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)
Run Code Online (Sandbox Code Playgroud)
截至今天,React 提供的当前类型似乎还没有一种“原生”方法可以做到这一点。你可以在 React 的 repo 上查看这个问题。最好的方法似乎是自己声明这些类型:
declare module 'react' {
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
// extends React's HTMLAttributes
directory?: string;
webkitdirectory?: string;
}
}
Run Code Online (Sandbox Code Playgroud)
根据这个问题的评论。
这种类型定义只会让 Typescript 感到冷淡,但请记住,React 会将它无法识别的 props 转发给底层 DOM 元素(又名<input />),即使 React 不知道这一点,也可以使这项工作正常进行(请查看React 网站上的这篇博客文章)。