【问题标题】:ReactJS - Adding attributes to a reference object created with useRef Hook?ReactJS - 向使用 useRef Hook 创建的引用对象添加属性?
【发布时间】:2021-02-27 15:20:54
【问题描述】:

在我的类组件中,我有一个 ref 对象来从选定文件夹中选择文件。所以,我在 componentDidMount 中添加属性 directorywebkitdirectory

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 反应钩子来使用文件夹引用。但是添加属性directorywebkitdirectory 不会将这些属性添加到我的文件夹选择输入中。也就是说,我的输入元素没有像在类组件中那样工作。 这是我的代码

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


【解决方案1】:

我没有看到你的错误信息,但我可以写出 useRef 的用法

const inputRef = useRef();

useEffect(() => {
  folderInput.current.setAttribute('directory', '');
 folderInput.current.setAttribute('webkitdirectory', '');
}, [folderInput]);


  return <Input ref={inputRef} /> ;

【讨论】:

  • 什么是文件夹输入?
  • 状态。正如您在问题上看到的那样
猜你喜欢
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 2020-01-08
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多