一些背景: 我正在尝试在 React 应用程序中使用一个自定义网络组件,并尝试监听来自该网络组件的事件。我相信您不能只在自定义 Web 组件上以通常的 react 方式处理事件。
即
<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
。
关于javascript - React 应用程序中的 addEventListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50530162/