• 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;
    

    open-file-input-on-button-click.gif

    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上模拟点击。

  • 相关阅读:
    氛围灯控制器VALS
    MongoDB工具命令和用户认证
    STM32物联网项目-通过ESP12S模块连接TCP服务器
    比尔·盖茨晒48年前简历:“没你们的好看”
    用katalon解决接口/自动化测试拦路虎--参数化
    介绍Spring MVC框架,以及如何使用它构建Web应用程序。
    pat 1009 说反话
    论开会的艺术
    在SQL中:如何使用命令创建、修改、添加数据库
    简单支付系统
  • 原文地址:https://www.cnblogs.com/chuckQu/p/16414452.html