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>
ref
prop을 사용하여 콜백을 통해 기본 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 ref
를 div
노드로 설정
<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
'IT TIP' 카테고리의 다른 글
오류 aws ecs list-container-instances 명령을 실행할 때 지역을 지정해야합니다. (0) | 2020.12.11 |
---|---|
XCode 6.4에서 대상 도구 모음이 사라졌습니다. (0) | 2020.12.11 |
플랫 번들링이란 무엇이며 롤업이 Webpack보다 더 나은 이유는 무엇입니까? (0) | 2020.12.11 |
jQuery UI 대화 버튼 포커스 (0) | 2020.12.11 |
다른 방법은 없습니다. (0) | 2020.12.11 |