React 应用程序中的 addEventListener 不起作用 [英] addEventListener in a React app isn't working

查看:79
本文介绍了React 应用程序中的 addEventListener 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Some background: I'm trying to consume a custom web component in a react app and trying to listen to events from the web component. I believe you can't just handle the events in the usual react way on custom web component.

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

我已经试过了,但没有用.

I have tried this and it didn't work.

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

The problem: So, I'm trying to listen to an event via addEventListener as you would do in vanilla js but the event handler is never getting called.

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

An example of this is below. I know <button/> isn't a custom web component but it demonstrates the problem:

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.

这篇关于React 应用程序中的 addEventListener 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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