itsource

ReactJS에서 클릭 이벤트를 수동으로 트리거하는 방법

mycopycode 2023. 3. 23. 22:44
반응형

ReactJS에서 클릭 이벤트를 수동으로 트리거하는 방법

ReactJS에서 클릭 이벤트를 수동으로 트리거하려면 어떻게 해야 합니까?사용자가 요소 1을 클릭하면 자동으로 클릭을 트리거합니다.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>

콜백을 통해 기본 HTMLInputElement 객체에 대한 참조를 취득하고 참조를 클래스 속성으로 저장한 후 이 참조를 사용하여 나중에 HTMLlement.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;

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>
    );
}

사용할 수 있습니다.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/

도움이 됐으면 좋겠다!

기능적인 컴포넌트에서도 이 원리는 기능합니다.이것은 단지 구문과 사고방식이 조금 다를 뿐입니다.

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>
    </>
  )

}

Aaron Hakala의 답변에 대해 useRef를 사용하여 이 답변에서 영감을 얻은 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}>

리액트 훅과 을 사용합니다.

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>
    );
}
this.buttonRef.current.click();

이것을 사용해 보고, 동작하지 않는 경우는, 다음과 같이 알려 주세요.

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

를 클릭합니다.div를 클릭하는 시뮬레이션을 실시합니다.input요소

  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>

typescript의 경우 이 코드를 사용하여 type 오류가 발생하지 않도록 할 수 있습니다.

import React, { useRef } from 'react';

const MyComponent = () => {
    const fileRef = useRef<HTMLInputElement>(null);

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

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

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();
  }
}

  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>

이것은 나에게 효과가 있다.

plain old js는 어떻습니까?예:

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

반응형