Html 如何在 ReactJS 中手动触发点击事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39913863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:54:16  来源:igfitidea点击:

How to manually trigger click event in ReactJS?

htmlreactjs

提问by Mamata Hegde

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

如何在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>

回答by John Weisz

You could use the refprop to acquire a reference to the underlying HTMLInputElementobject 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.clickmethod.

您可以使用refprop通过回调获取对底层HTMLInputElement对象的引用,将引用存储为类属性,然后使用该引用稍后使用HTMLElement.click方法从事件处理程序触发单击。

In your rendermethod:

在你的render方法中:

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

In your event handler:

在您的事件处理程序中:

this.inputElement.click();

Full example:

完整示例:

class MyComponent extends React.Component {
  render() {
    return (
      <div onClick={this.handleClick}>
        <input ref={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

Note the ES6 arrow functionthat provides the correct lexical scope for thisin 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.

请注意ES6 箭头函数,它为this回调提供了正确的词法范围。另请注意,您以这种方式获取的对象类似于您将使用 获取的对象document.getElementById,即实际的 DOM 节点。

回答by Sir Codes Alot

Got the following to work May 2018 with ES6 React Docs as a reference: https://reactjs.org/docs/refs-and-the-dom.html

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

回答by Pranesh Ravi

You can use refcallback which will return the node. Call click()on that node to do a programmatic click.

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

Getting the divnode

获取div节点

clickDiv(el) {
  el.click()
}

Setting a refto the divnode

refdiv节点设置a

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

Check the fiddle

检查小提琴

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

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

Hope it helps!

希望能帮助到你!

回答by Immutable Brick

In a functional component this principle also works, it's just a slightly different syntax and way of thinking.

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

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

}

回答by Alex Oleksiiuk

Try this and let me know if it does not work on your end:

试试这个,让我知道它是否对你不起作用:

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

Clicking on the divshould simulate a click on the inputelement

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

回答by mXaln

If it doesn't work in the latest version of reactjs, try using innerRef

如果它在最新版本的 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();
  }
}

回答by sajad saderi

Here are the Hooks solution

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

回答by arslan

  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>

This work for me

这对我有用

回答by taggartJ

How about just plain old js ? example:

只是普通的旧 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>
);