如何在ReactJS中手动触发click事件?

Mam*_*gde 59 html reactjs react-jsx

如何在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>
Run Code Online (Sandbox Code Playgroud)

Joh*_*isz 86

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

在你的render方法中:

<input ref={input => this.inputElement = input} ... />
Run Code Online (Sandbox Code Playgroud)

在事件处理程序中:

this.inputElement.click();
Run Code Online (Sandbox Code Playgroud)

完整示例:

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

  handleClick = (e) => {
    this.inputElement.click();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • "Refs不再返回文档DOM节点,它们返回对React虚拟DOM节点的引用"这绝对是一种误解.Refs不返回"虚拟DOM"节点.资料来源:我在React工作. (19认同)
  • 这不适合我.不确定它是否已过时,但我成功分配了元素,但当我在其上调用"click"时,"click"未定义.我可以看到我分配给该元素的所有其他属性和回调.有任何想法吗? (6认同)
  • @DanAbramov那么推荐的方法是什么? (2认同)
  • @TheJKFever 如果您使用的是 TypeScript,则单击可能未定义,因为输入是类型;`HTMLInputElement | null;`,因此使用:`onClick={() =&gt; { if(inputElement) (inputElement).click(); } }` 让它编译! (2认同)

小智 14

通过ES6 React Docs作为参考,获得以下工作:2018年5月: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;
Run Code Online (Sandbox Code Playgroud)


Saj*_*eri 10

这是 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>
     );
    }
Run Code Online (Sandbox Code Playgroud)

  • “myRefname.current.focus 不是一个函数” (11认同)
  • 很好的答案,使用“myRefname.current.click();” (2认同)

Pra*_*avi 9

您可以使用ref将返回的回调node.调用click()该节点进行程序化点击.

获取div节点

clickDiv(el) {
  el.click()
}
Run Code Online (Sandbox Code Playgroud)

将a设置refdiv节点

<div 
  id="element1"
  className="content"
  ref={this.clickDiv}
  onClick={this.uploadLogoIcon}
>
Run Code Online (Sandbox Code Playgroud)

检查小提琴

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

希望能帮助到你!

  • 值得注意的是,虽然字符串引用方法不被弃用,但它被认为是基于回调的语法取代的遗留功能:`ref = {elem => this.elem = elem}` - 这在[详细说明]中有详细说明.参考组件](https://facebook.github.io/react/docs/more-about-refs.html). (4认同)

Fun*_*ing 8

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

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

}
Run Code Online (Sandbox Code Playgroud)


小智 8

this.buttonRef.current.click();
Run Code Online (Sandbox Code Playgroud)

  • 这解决了我的问题,我不知道为什么人们取消对这段代码的投票 (2认同)

小智 6

受此答案启发,利用 useRef 反复研究 Aaron Hakala 的答案/sf/answers/3802145791/

const myRef = useRef(null);

  const clickElement = (ref) => {
    ref.current.dispatchEvent(
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,
      }),
    );
  };
Run Code Online (Sandbox Code Playgroud)

还有你的 JSX:

<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>
Run Code Online (Sandbox Code Playgroud)


Aar*_*ala 5

使用 React Hooks 和useRefhook

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>
    );
}
Run Code Online (Sandbox Code Playgroud)