如何在 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>
269933 次浏览

您可以使用 ref回调,它将返回 node.Callclick()在该节点上进行编程式单击。

获取 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/

希望能有帮助!

您可以使用 ref道具通过回调获取对底层 HTMLInputElement对象的引用,将引用存储为 class 属性,然后使用该引用以后使用 点击 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 as a reference: https://reactjs.org/docs/refs-and-the-dom.html反应文档作为参考: 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;

就普通的 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>
);

试试这个,让我知道如果它不工作,你的一端:

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

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

在函数组件中,这个原则也有效,只是语法和思维方式略有不同。

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


}

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

下面是胡克斯的解决方案:

import React, {useRef} from 'react';


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


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

  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>

这对我有用

使用反应钩和 useRef钩子

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

受这个答案的启发,用 useRef 对 Aaron Hakala 的答案进行了即兴演绎

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

对于打印脚本,您可以使用此代码来避免得到类型错误

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