IT TIP

ReactJS에서 클릭 이벤트를 수동으로 트리거하는 방법은 무엇입니까?

itqueen 2020. 12. 11. 21:10
반응형

ReactJS에서 클릭 이벤트를 수동으로 트리거하는 방법은 무엇입니까?


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>

refprop을 사용하여 콜백을 통해 기본 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 화살표 함수에 유의하십시오 this. 또한이 방법으로 획득 한 객체는를 사용하여 획득 할 수있는 객체 document.getElementById, 즉 실제 DOM 노드 와 유사한 객체 입니다.


다음은 2018 년 5 월 ES6 React Docs를 참조로 사용하여 작동합니다 : 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;

ref을 반환하는 콜백을 사용할 수 있습니다 node. click()해당 노드를 호출 하여 프로그래밍 방식으로 클릭합니다.

div노드 얻기

clickDiv(el) {
  el.click()
}

a refdiv노드로 설정

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

바이올린 확인

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

도움이 되었기를 바랍니다.


이것을 시도하고 그것이 작동하지 않는 경우 알려주십시오.

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

Clicking on the div should simulate a click on the input element


How about just plain old js ? example:

autoClick = () => {
 if (something === something) {
    var link = document.getElementById('dashboard-link');
    link.click();
  }
};
  ......      
var clickIt = this.autoClick();            
return (
  <div>
     <Link id="dashboard-link" to={'/dashboard'}>Dashboard</Link>
  </div>
);

참고URL : https://stackoverflow.com/questions/39913863/how-to-manually-trigger-click-event-in-reactjs

반응형