原文链接:https://bobbyhadz.com/blog/react-open-file-input-on-button-click
作者:Borislav Hadzhiev
注释从这开始~
总览
在React中,通过点击按钮,关上文件输入框:
- 在
button
元素上设置onClick
属性。 - 在文件输入框上设置
ref
属性。 - 当按钮被点击时,关上文件输入框。比如说,
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
上模仿点击。