# React技巧之打开文件输入框
原文链接:https://bobbyhadz.com/blog/react-open-file-input-on-button-click (opens new window)
作者:Borislav Hadzhiev (opens new window)
正文从这开始~
# 总览
在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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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上模拟点击。