javascript 如何通过另一个 DOM 触发 INPUT FILE 事件 REACTJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32433594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trigger INPUT FILE event REACTJS by another DOM
提问by Yarin Nim
I have a INPUT BUTTONand INPUT FILE, I want to click the BUTTONand it will trigger the INPUT FILEevent in REACT JS.
我有一个INPUT BUTTON和INPUT FILE,我想单击BUTTON它将触发REACT JS 中的INPUT FILE事件。
React.createElement('input',{type:'file', name:'myfile'})
then the button
然后按钮
React.createElement('a',{onClick: this.doClick},'Select File')
So how to define and trigger the INPUT FILE click event when we click the A HREF?
那么当我们点击A HREF时,如何定义和触发INPUT FILE点击事件呢?
Your help is appreciate. :-)
感谢您的帮助。:-)
采纳答案by Fran?ois Richard
You can achieve this using jQuery:
您可以使用 jQuery 实现此目的:
this.doClick: function() {
$('input[type=file]').trigger('click');
}
React does not provide specific functions to trigger events, you can use jQuery or simply native Javascript: see Creating and triggeringevents on MDN
React 不提供触发事件的特定函数,您可以使用 jQuery 或简单的原生 Javascript:参见MDN 上的创建和触发事件
回答by Bart S
You don't need jQuery for this. You don't even need an event handler. HTML has a specific element for this, called label.
为此,您不需要 jQuery。您甚至不需要事件处理程序。HTML 为此有一个特定的元素,称为label。
First, make sure your input
element has an id
attribute:
首先,确保你的input
元素有一个id
属性:
React.createElement('input',{type:'file', name:'myfile', id:'myfile'})
Then, instead of:
然后,而不是:
React.createElement('a',{onClick: this.doClick},'Select File')
Try:
尝试:
React.createElement('label',{htmlFor: 'myfile'},'Select File')
(Instead of adding htmlFor
and id
attributes, another solution is to make the input
element a child of the label
.)
(而不是添加htmlFor
和id
属性,另一种解决方案是使input
元素成为 的子元素label
。)
Now clicking the label
should trigger the same behaviour as clicking the input
itself.
现在点击label
应该触发与点击input
本身相同的行为。
回答by Fidel Ramadhan
You could trigger the input type file with ref, f.e:
您可以使用 ref, fe 触发输入类型文件:
on your class component:
在您的类组件上:
<input
ref={fileInput => this.fileInput = fileInput}
type="file"
/>
<button onClick={this.triggerInputFile}> Select File </button>
and make a function on that class component too:
并在该类组件上创建一个函数:
triggerInputFile = () => this.fileInput.click()
回答by YòG?
Using useRefHook in functional components. Requires React ^16.8,
在功能组件中使用useRefHook。需要反应 ^16.8,
const Dummy = () => {
const inputFileRef = useRef(null);
const handleBtnClick = () => {
/*Collecting node-element and performing click*/
inputFileRef.current.click();
}
return (
<form className="some-container">
<input type="file" ref={inputFileRef} />
<button onClick={onBtnClick}>Select file</button>
</form >
)
}
Class Implementation with React.createRef()and handling click with node element.
使用React.createRef()实现类并使用节点元素处理点击。
class Dummy extends React.Component {
constructor(props) {
super(props);
this.inputFileRef = React.createRef();
this.onBtnClick = this.handleBtnClick.bind(this)
}
handleBtnClick() {
/*Collecting node-element and performing click*/
this.inputFileRef.current.click();
}
render() {
return (
<form className="some-container">
<input type="file" ref={this.inputFileRef} />
<button onClick={this.onBtnClick}>Select file</button>
</form>
)
}
}
回答by Farid Murzone
Using Hooks with useref:
使用带有 userref 的钩子:
import React, {useRef} from 'react';
const FancyInput = () => {
const fileInput = useRef(null)
const handleClick = () => {
fileInput.current.click()
}
const handleFileChange = event => {
console.log("Make something")
}
return(
<div className="patientactions-container">
<input
type="file"
onChange={(e) => handleFileChange(e)}
ref={fileInput}
/>
<div onClick={() => handleClick()}></div>
</div>
)
}
export default FancyInput;
回答by Michael Osofsky
Building on the answer from @YòG? , here is an implementation using TypeScript:
以@YòG 的答案为基础?,这是一个使用 TypeScript 的实现:
class Dummy extends React.Component {
fileInputRef: React.RefObject<HTMLInputElement> = React.createRef();
forwardClickToInputElement = () => {
this.fileInputRef.current!.click();
};
handleUploadDemand = (ie: ChangeEvent<HTMLInputElement>) => {
const fileList: FileList = ie.target.files;
// do something with the FileList, for example:
const fileReader = new FileReader();
fileReader.onload = () => {
const str = String(fileReader.result);
try {
const parsedContent = YOUR_OWN_PARSING(str);
} catch (error) {
// YOUR OWN ERROR HANDLING
}
};
fileReader.readAsBinaryString(fileList[0])
}
render() {
return (
<div className="some-container">
<button onClick={this.forwardClickToInputElement}>Select File</button>
<input ref={this.fileInputRef} type="file" onChange={this.handleSelectFile} hidden={true}/>
</div>
)
}
}
References:
参考:
- Solution for how to use refs in React with Typescript https://stackoverflow.com/a/50505931/2848676
- Use ! operator for ref type narrowing https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315
- 如何在 React 中使用 refs with Typescript https://stackoverflow.com/a/50505931/2848676 的解决方案
- 利用 !用于缩小引用类型的运算符https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315