如何通过其他DOM触发INPUT FILE事件REACTJS

wooyq4lh  于 2023-08-04  发布在  React
关注(0)|答案(9)|浏览(127)

我有一个INPUT BUTTONINPUT FILE,我想点击BUTTON,就会触发REACT JS中的INPUT FILE事件。

React.createElement('input',{type:'file', name:'myfile'})

字符串
然后按钮

React.createElement('a',{onClick: this.doClick},'Select File')


那么,当我们单击A HREF时,如何定义和触发INPUT FILE单击事件呢?
感谢你的帮助。:-)

xwmevbvl

xwmevbvl1#

更新时间:2021年9月18日

注意:在NextJS上,我遇到的是onChange事件不是从输入文件元素触发的。我们可以使用onInputCaptureonChangeCapture。有关更多详细信息,请参阅Stackoverflow - onChange event is not firing
onChangeCapture上的基本示例根据我们的要求。需要React ^16.8,

const Dummy = () => {
  const inputFileRef = React.useRef();
  const onFileChangeCapture = ( e: React.ChangeEvent<HTMLInputElement> ) {
    /*Selected files data can be collected here.*/
    console.log(e.target.files);
  };
  const onBtnClick = () => {
    /*Collecting node-element and performing click*/
    inputFileRef.current.click();
  };
  return (
    <form>
      <input
        type="file"
        ref={inputFileRef}
        onChangeCapture={onFileChangeCapture}
      />
      <button onClick={onBtnClick}>Select file</button>
    </form>
  );
};

字符串
在功能组件中使用useRefHook。需要React ^16.8,

const Dummy = () => {
  const inputFileRef = useRef( null );

  const onFilechange = ( e ) => {
    /*Selected files data can be collected here.*/
    console.log( e.target.files );
  }
  const onBtnClick = () => {
    /*Collecting node-element and performing click*/
    inputFileRef.current.click();
  }

  return (
    <form className="some-container">
      <input
        type="file"
        ref={inputFileRef}
        onChange={onFileChange}
      />
      <button onClick={onBtnClick}>Select file</button>
    </form>
  )
}


类实现与React.createRef(),处理单击与node element

class Dummy extends React.Component {
    
  constructor( props ) {
    super( props );

    this.inputFileRef = React.createRef();
    this.onFileChange = this.handleFileChange.bind( this );
    this.onBtnClick = this.handleBtnClick.bind( this );
  }

  handleFileChange( e ) {
    /*Selected files data can be collected here.*/
    console.log( e.target.files );
  }

  handleBtnClick() {
    /*Collecting node-element and performing click*/
    this.inputFileRef.current.click();
  }

  render() {
    return (
      <form className="some-container">
        <input
          type="file"
          ref={this.inputFileRef}
          onChange={this.onFileChange}
        />
        <button onClick={this.onBtnClick}>Select file</button>
      </form>
    )
  }
}

zed5wv10

zed5wv102#

你不需要jQuery。你甚至不需要事件处理程序。HTML有一个特定的元素,叫做label
首先,确保input元素具有id属性:

React.createElement('input',{type:'file', name:'myfile', id:'myfile'})

字符串
然后,而不是:

React.createElement('a',{onClick: this.doClick},'Select File')


试试看:

React.createElement('label',{htmlFor: 'myfile'},'Select File')


(另一种解决方案是将input元素作为label的子元素,而不是添加htmlForid属性。
现在单击label应该触发与单击input本身相同的行为。

wb1gzix0

wb1gzix03#

您可以使用ref,f.e触发输入类型文件:
在类组件上:

<input 
    ref={fileInput => this.fileInput = fileInput} 
    type="file"
 />
<button onClick={this.triggerInputFile}> Select File </button>

字符串
并在该类组件上创建一个函数:

triggerInputFile = () => this.fileInput.click()

jqjz2hbq

jqjz2hbq4#

使用Hooks和useref:

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;

字符串

z9zf31ra

z9zf31ra5#

基于@ 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>
        )
    }
}

字符串
参考文献:
1.如何在React with Typescript https://stackoverflow.com/a/50505931/2848676中使用refs的解决方案
1.使用!运算符用于ref类型收缩https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315

ippsafx7

ippsafx76#

const CustomInput = () => {
  const handleClick = () => {
    document.getElementById("file_upload").click();
  };

  const handleFileChange = (event) => {
    console.log("Make something");
  };

  return (
    <div className="patientactions-container">
      <input type="file" id="file_upload" onChange={(e) => handleFileChange(e)} />
      <div onClick={() => handleClick()}></div>
    </div>
  );
};
export default CustomInput;

字符串

wfauudbj

wfauudbj7#

对于那些想要在Typescript中实现Farid's答案的人,可以做以下操作:

import React, {useRef} from 'react';
const FancyInput = () => {
  const fileInput = useRef<HTMLDivElement>(null)

  const handleClick = () => {
    if(fileInput.current) {
      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;

字符串

zdwk9cvp

zdwk9cvp8#

任何人寻找一个简单的方法尝试这个。

<div>
  <input type="file" name="library-images" id="library-images" hidden />
     <Button type='button' onClick={()=>{
                document.getElementById("library-images")?.click()
     }}>Upload</Button>
</div>

字符串

e0bqpujr

e0bqpujr9#

**编辑:**这是我很久以前回答的问题,当时不知道有多少React。有趣的是,它被认为是有效的^^。

对于任何阅读这个答案的人来说;这个答案是错误的,是一个很好的例子,说明了你不应该在react中做的事情。
请在下面找到
一个很好的反模式**,再一次,**不要这样做。

你可以使用jQuery来实现这一点:

this.doClick: function() {
    $('input[type=file]').trigger('click');
}

字符串
React不提供特定的函数来触发事件,你可以使用jQuery或简单的原生JavaScript:参见MDN上的Creating and triggering事件

相关问题