如何在ReactJS中手动触发点击事件? [英] How to manually trigger click event in ReactJS?

查看:2779
本文介绍了如何在ReactJS中手动触发点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何手动触发 ReactJS 中的点击事件?
当用户点击element1时,我想自动触发对输入标签的点击。

 < div className =div-margins logoContainer> 
< div id =element1className =contentonClick = {this.uploadLogoIcon}>
< div className =logoBlank/>
< / div>
< input accept =image / *type =fileclassName =hide/>
< / div>


解决方案

您可以使用 ref 道具以获取对通过回调获取底层的 HTMLInputElement 对象,将引用存储为类属性,然后使用该引用以稍后使用渲染方法中:$ / $> $ / $>

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

在您的事件处理程序中:

  this.inputElement.click(); 

请注意 ES6箭头函数这个提供了正确的词法范围。回调。还要注意,以这种方式获得的对象与您使用 document.getElementById 获得的对象类似,即实际的DOM节点。


How can I manually trigger a click event in ReactJS? When a user clicks on element1, I want to automatically trigger a click on the input tag.

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

解决方案

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

In your render method:

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

In your event handler:

this.inputElement.click();

Note the ES6 arrow function that provides the correct lexical scope for this in the callback. Also note, that the object you acquire this way is an object akin to what you would acquire using document.getElementById, i.e. the actual DOM-node.

这篇关于如何在ReactJS中手动触发点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆