关于react.js:React技巧之打开文件输入框

原文链接:https://bobbyhadz.com/blog/react-open-file-input-on-button-click

作者:Borislav Hadzhiev

注释从这开始~

总览

在React中,通过点击按钮,关上文件输入框:

  1. button元素上设置onClick属性。
  2. 在文件输入框上设置ref属性。
  3. 当按钮被点击时,关上文件输入框。比如说,inputRef.current.click()
import {useRef} from 'react';

const App = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    // 👇️ open file input box on click of other element
    inputRef.current.click();
  };

  const handleFileChange = event => {
    const fileObj = event.target.files && event.target.files[0];
    if (!fileObj) {
      return;
    }

    console.log('fileObj is', fileObj);

    // 👇️ reset file input
    event.target.value = null;

    // 👇️ is now empty
    console.log(event.target.files);

    // 👇️ can still access file object here
    console.log(fileObj);
    console.log(fileObj.name);
  };

  return (
    <div>
      <input
        style={{display: 'none'}}
        ref={inputRef}
        type="file"
        onChange={handleFileChange}
      />

      <button onClick={handleClick}>Open file upload box</button>
    </div>
  );
};

export default App;

click

咱们应用useRef钩子拜访文件input元素。须要留神的是,咱们必须拜访ref对象上的current属性,以取得对咱们设置ref属性的文件input元素的拜访。

当咱们将ref属性传递到元素上时,比如说,<input type="file" ref={myRef} /> 。React将ref对象的.current属性设置为相应的DOM节点。

咱们调用了click()办法,比方:ref.current.click() 。以此来模仿input元素上的鼠标点击事件。

当对一个元素应用click()办法时,它会触发该元素的点击事件。当一个文件input的点击事件被触发时,文件上传对话框就会关上。

须要留神的是,咱们对input元素的display属性设置为none,来暗藏该元素。

当初,当用户点击button元素时,咱们在input元素上应用ref对象来模仿click事件,并且文件上传对话框会被关上。

总结

该办法能够在任何类型元素上失效,比如说div或者一个图标。只需在元素上设置onClick属性,当元素被点击时,就能够文件input上模仿点击。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理