【发布时间】:2021-02-27 15:20:54
【问题描述】:
在我的类组件中,我有一个 ref 对象来从选定文件夹中选择文件。所以,我在 componentDidMount 中添加属性 directory 和 webkitdirectory 为
export class ImportForm extends React.Component<ImportFormProps,ImportFormState> {
constructor(props:ImportFormProps){
super(props);
this.state={
folderInput: React.createRef()
}
}
componentDidMount(){
if (this.state.folderInput.current !== null) {
this.state.folderInput.current.setAttribute("directory", "");
this.state.folderInput.current.setAttribute("webkitdirectory", "");
}
}
.
.
.
我正在将上面的类组件更改为 FunctionComponent。现在,我正在使用 useRef 反应钩子来使用文件夹引用。但是添加属性directory 和webkitdirectory 不会将这些属性添加到我的文件夹选择输入中。也就是说,我的输入元素没有像在类组件中那样工作。
这是我的代码
export const ImportForm : React.FunctionComponent<ImportFormProps> = (
props
) => {
const folderInput = React.useRef(null);
React.useEffect(() => {
if (folderInput.current !== null) {
folderInput.current.setAttribute("directory", "");
folderInput.current.setAttribute("webkitdirectory", "");
}
}, [folderInput]);
useEffect hook 是否适合添加这些属性?
我做错了什么?
我尝试了this solution,但没有成功。
谢谢!
【问题讨论】:
-
嗨。你解决了这个问题吗?
标签: reactjs react-hooks