React 应用程序中的 addEventListener 不起作用

addEventListener in a React app isn't working

一些背景: 我正在尝试在 React 应用程序中使用 自定义 Web 组件 并尝试侦听来自 Web 组件的事件。我相信您不能只在自定义 Web 组件上以通常的反应方式处理事件。

<custom-button onClick={this.clickHandler}></custom-button>.  

我试过了,没用。

问题: 因此,我正在尝试通过 addEventListener 来收听事件,就像您在 vanilla js 中所做的那样,但事件处理程序永远不会被调用。

下面是一个例子。我知道 <button/> 不是自定义 Web 组件,但它说明了问题:

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.buttonRef = React.createRef();
  }
  componentDidMount() {
    // there are no errors attaching the handler
    this.buttonRef.current.addEventListener("onClick", e => {
      // this point is never reached
      debugger;
      console.log("onClick", e);
    });
  }
  render() {
    return <button ref={this.buttonRef}>click me</button>;
  }
}

export default App;

如有任何帮助,我们将不胜感激。

活动名为 click,而不是 onClick

您无需使用 eventListener 即可。在ReactJS中,你可以在按钮上使用一个handler,像这样:

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
  }
  btnHandler = e => {
      console.log("onClick",e)
  }
  render() {
    return <button onClick={this.btnHandler}> click me </button>
  }
} 

export default App;

看看ReactJS Handling Events docs

您在这里混合了两种功能, button 只会对 onClick 事件做出反应,如果点击了 ref,你的 ref 只会对 'click' 做出反应,但事实并非如此。 所以该按钮目前没有任何功能。

来自反应文档:

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  let textInput = React.createRef();

  function handleClick() {
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />

      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

这是您问题的解决方案。希望是正确的解决方案。

还有 <button onClick={this.onClick}>click me</button>

可以写成: <button onClick={e => this.onClick({e, ...})}>click me</button>

访问您想要传递给按钮事件侦听器的自定义道具。 在这种情况下,您的事件监听器需要看起来像:

onClick = (e, ...) => { // this point is never reached debugger; console.log("onClick", e); };

请注意其中的 ... 需要一对 key => value

import React, { Component } from "react";

export default class App extends Component {
  constructor(props) {
    super(props);
  }

  onClick = e => {
      // this point is never reached
      debugger;
      console.log("onClick", e);
  };

  render() {
    return <button onClick={this.onClick}>click me</button>;
  }
}

另外尽量不要使用 React 引用,除非你真的需要。它们不打算在 React 的核心功能之外使用。