How to trigger INPUT FILE event REACTJS by another DOM

后端 未结 6 965
-上瘾入骨i
-上瘾入骨i 2021-01-02 01:53

I have a INPUT BUTTON and INPUT FILE, I want to click the BUTTON and it will trigger the INPUT FILE event

6条回答
  •  被撕碎了的回忆
    2021-01-02 02:34

    Building on the answer from @YÒGÎ , here is an implementation using TypeScript:

    class Dummy extends React.Component {
        fileInputRef: React.RefObject = React.createRef();
    
        forwardClickToInputElement = () => {
            this.fileInputRef.current!.click();
        };
    
        handleUploadDemand = (ie: ChangeEvent) => {
            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 (
                
    ) } }

    References:

    1. Solution for how to use refs in React with Typescript https://stackoverflow.com/a/50505931/2848676
    2. Use ! operator for ref type narrowing https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315

提交回复
热议问题