如何检测类外组件的点击



我的任务是检测组件外部的点击。我一直试图用typescript实现下面的代码,但找不到应该给handleClickOutside事件什么类型,这样event.target就不会抛出错误:Argument of type 'EventTarget | null' is not assignable to parameter of type 'Node | null'。不允许使用挂钩。请帮忙。

import React, { Component } from "react";
export default class OutsideAlerter extends Component {
private wrapperRef: React.RefObject<HTMLInputElement>;
constructor(props) {
super(props);
this.wrapperRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
handleClickOutside(event) { //problem is here
if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) { //and here
alert("You clicked outside of me!");
}
}
render() {
return <div ref={this.wrapperRef}>{this.props.children}</div>;
}
}

您必须为事件分配一个类型,请注意,由于您正在文档上注册处理程序,因此需要指定该类型。

handleClickOutside(event: React.MouseEvent<Document>) {

请参阅https://www.carlrippon.com/React-event-handlers-with-typescript/