How to trigger INPUT FILE event REACTJS by another DOM

后端 未结 6 962
-上瘾入骨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:33

    Using useRef Hook in functional components. Requires 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 handleBtnClick = () => {
        /*Collecting node-element and performing click*/
        inputFileRef.current.click();
      }
    
      return (
        
    ) }

    Class Implementation with React.createRef() and handling click with 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 (
          
    ) } }

提交回复
热议问题