如何在ReactJS中手动触发click事件?

时间:2016-10-07 09:24:52

标签: html reactjs react-jsx

如何在 ReactJS 中手动触发点击事件? 当用户点击element1时,我想自动触发input标记上的点击。

<div className="div-margins logoContainer">
  <div id="element1" className="content" onClick={this.uploadLogoIcon}>
    <div className="logoBlank" />
  </div>
  <input accept="image/*" type="file" className="hide"/>
</div>

13 个答案:

答案 0 :(得分:73)

您可以使用ref道具通过回调获取对基础HTMLInputElement对象的引用,将引用存储为类属性,然后使用该引用稍后触发事件中的单击处理程序使用HTMLElement.click方法。

render方法中:

<input ref={input => this.inputElement = input} ... />

在您的事件处理程序中:

this.inputElement.click();

完整示例:

class MyComponent extends React.Component {
  render() {
    return (
      <div onClick={this.handleClick}>
        <input ref={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

注意ES6 arrow function在回调中为this提供了正确的词法范围。另请注意,以这种方式获取的对象是一个类似于使用document.getElementById获取的对象,即实际的DOM节点。

答案 1 :(得分:14)

通过ES6获得以下工作于2018年5月 将文档作为参考:https://reactjs.org/docs/refs-and-the-dom.html

import React, { Component } from "react";
class AddImage extends Component {
  constructor(props) {
    super(props);
    this.fileUpload = React.createRef();
    this.showFileUpload = this.showFileUpload.bind(this);
  }
  showFileUpload() {
    this.fileUpload.current.click();
  }
  render() {
    return (
      <div className="AddImage">
        <input
          type="file"
          id="my_file"
          style={{ display: "none" }}
          ref={this.fileUpload}
        />
        <input
          type="image"
          src="http://www.graphicssimplified.com/wp-content/uploads/2015/04/upload-cloud.png"
          width="30px"
          onClick={this.showFileUpload}
        />
      </div>
    );
  }
}
export default AddImage;

答案 2 :(得分:10)

您可以使用ref回调来返回node。在该节点上调用click()进行程序化点击。

获取div节点

clickDiv(el) {
  el.click()
}

ref设置为div节点

<div 
  id="element1"
  className="content"
  ref={this.clickDiv}
  onClick={this.uploadLogoIcon}
>

检查小提琴

https://jsfiddle.net/pranesh_ravi/5skk51ap/1/

希望它有所帮助!

答案 3 :(得分:3)

这是Hooks解决方案

    import React, {useRef} from 'react';

    const MyComponent = () =>{

    const myRefname= useRef(null);

    const handleClick = () => {
        myRefname.current.focus();
     }

    return (
      <div onClick={handleClick}>
        <input ref={myRefname}/>
      </div>
     );
    }

答案 4 :(得分:1)

使用React Hooks和useRef hook

import React, { useRef } from 'react';

const MyComponent = () => {
    const myInput = useRef(null);

    const clickElement = () => {
        // To simulate a user focusing an input you should use the
        // built in .focus() method.
        myInput.current?.focus();

        // To simulate a click on a button you can use the .click()
        // method.
        // myInput.current?.click();
    }

    return (
        <div>
            <button onClick={clickElement}>
                Trigger click inside input
            </button>
            <input ref={myInput} />
        </div>
    );
}

答案 5 :(得分:1)

根据use {Ref。https://stackoverflow.com/a/54316368/3893510

const myRef = useRef(null);

  const clickElement = (ref) => {
    ref.current.dispatchEvent(
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,
      }),
    );
  };

还有您的JSX:

<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>

答案 6 :(得分:0)

尝试一下,让我知道它是否对您不利:

<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>

点击div应该模拟点击input元素

答案 7 :(得分:0)

在功能组件中,该原理也有效,只是语法和思维方式略有不同。

const UploadsWindow = () => {
  // will hold a reference for our real input file
  let inputFile = '';

  // function to trigger our input file click
  const uploadClick = e => {
    e.preventDefault();
    inputFile.click();
    return false;
  };

  return (
    <>
      <input
        type="file"
        name="fileUpload"
        ref={input => {
          // assigns a reference so we can trigger it later
          inputFile = input;
        }}
        multiple
      />

      <a href="#" className="btn" onClick={uploadClick}>
        Add or Drag Attachments Here
      </a>
    </>
  )

}

答案 8 :(得分:0)

如果在最新版本的reactjs中不起作用,请尝试使用innerRef

class MyComponent extends React.Component {


  render() {
    return (
      <div onClick={this.handleClick}>
        <input innerRef={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

答案 9 :(得分:0)

  imagePicker(){
        this.refs.fileUploader.click();
        this.setState({
            imagePicker: true
        })
    }
  <div onClick={this.imagePicker.bind(this)} >
  <input type='file'  style={{display: 'none'}}  ref="fileUploader" onChange={this.imageOnChange} /> 
  </div>

为我工作

答案 10 :(得分:0)

  let timer;
  let isDoubleClick = false;

  const handleClick = () => {
    if(!isDoubleClick) {
      isDoubleClick = true;
      timer = setTimeout(() => {
        isDoubleClick = false;
        props.onClick();
      }, 200);
    } else {
      clearTimeout(timer);
      props.onDoubleClick();
    }
  }

return <div onClick={handleClick}></div>

答案 11 :(得分:-1)

那只是普通的旧js呢? 例如:

bool(false)

答案 12 :(得分:-2)

this.buttonRef.current.click();