尝试使用此代码中的包含内容。
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert("You clicked outside of me!");
}
export interface DatePickerProps {
wrapperRef?: any;
}
export class DatePicker extends React.Component<DatePickerProps> {
private wrapperRef: React.RefObject<HTMLDivElement>;
constructor(props: DatePickerProps) {
super(props);
this.wrapperRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener("mousedown", (e: Event) =>
this.handleClickOutside(e)
);
}
handleClickOutside(event: Event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return <div ref={this.wrapperRef}>{this.props.children}</div>;
}
}
export default DatePicker;
我需要.contains告诉我节点的存在。