【问题标题】:How to make Select Directory using React?如何使用 React 制作选择目录?
【发布时间】:2019-12-10 22:48:59
【问题描述】:
我需要将文件夹中的所有文件上传到服务器。
我正在尝试实现选择目录窗口,而不是选择文件。
正常方式如:
<input type="file" webkitdirectory directory/>
对我不起作用,并显示了“选择文件”窗口。
但是当我使用这个输入标签创建空的常规 html 文件时,它工作正常。
有人知道如何使用 React 实现解决方案吗?
谢谢!
【问题讨论】:
标签:
html
reactjs
folderbrowserdialog
【解决方案1】:
在带有 Typescript 的 React 17 中,如果你使用 useRef Hook,最好的办法是扩展 React 的 HTMLAttributes(在你输入的同一个文件中),然后在输入中简单地添加 directory 和 webkitdirectory 属性标记为
import * as React from "react";
export const ImportForm: React.FunctionComponent<FormProps> = (props) => {
const folderInput= React.useRef(null);
return (
<>
<div className="form-group row">
<div className="col-lg-6">
<label>Select Folder</label>
</div>
<div className="col-lg-6">
<input
type="file"
directory=""
webkitdirectory=""
className="form-control"
ref={folderInput}
/>
</div>
</div>
</>)
};
declare module 'react' {
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
// extends React's HTMLAttributes
directory?: string; // remember to make these attributes optional....
webkitdirectory?: string;
}
}
【解决方案2】:
试试bheptinh。
<input directory="" webkitdirectory="" type="file" />