gpt4 book ai didi

javascript - 如何引用组件并监听外部点击?

转载 作者:行者123 更新时间:2023-11-30 19:34:36 36 4
gpt4 key购买 nike

所以我正在尝试制作下拉选项组件。我想通过单击按钮来显示它,如果在此组件之外检测到单击,则将其隐藏。

这是一个代码。我做了 ref,但我不明白如何检查点击是否在组件上:

import React, { Component } from 'react'
import './OptionsMenu.sass'

import DropdownBox from '../DropdownBox/DropdownBox'
import Icon from '../Icon/Icon'

class OptionsMenu extends Component {
constructor(){
super()
this.dropdownBoxRef = React.createRef()
}

handleClickOutside = event => {
if (this.dropdownBoxRef && !this.dropdownBoxRef.contains(event.target)) {
this.props.close()
}
}

componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside)
}

componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside)
}

render() {
const options = this.props.options.map(option => (
<li className='OptionsList-Element'>
<div className='OptionsList-ElementIcon'>
<Icon name={option.icon} />
</div>
<span>{option.label}</span>
</li>
))
return (
<DropdownBox ref={this.dropdownBoxRef} styles={this.props.styles}>
<ul className='OptionsList'>{options}</ul>
</DropdownBox>
)
}
}

export default OptionsMenu

使用这段代码我有错误:OptionsMenu.js:14 Uncaught TypeError: _this.dropdownBoxRef.contains 不是函数

我知道错误,因为它没有 .contains()。那么我必须尝试使用​​什么?

最佳答案

请找到有助于解决您的问题的更新代码:

import ReactDOM from "react-dom";

import "./styles.css";
import React, { Component } from "react";

class OptionsMenu extends Component {
constructor() {
super();
this.dropdownBoxRef = React.createRef();
}

handleClickOutside = event => {
if (this.dropdownBoxRef && !this.dropdownBoxRef.current.contains(event.target)) {
this.props.close();
}
};

componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}

componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}

render() {
const options = ["a", "b", "c"].map(option => (
<li className="OptionsList-Element">
<div className="OptionsList-ElementIcon">Icon</div>
<span>{option.label}</span>
</li>
));
return (
<div ref={this.dropdownBoxRef} styles={this.props.styles}>
<ul className="OptionsList">{options}</ul>
</div>
);
}
}

export default OptionsMenu;

const rootElement = document.getElementById("root");
ReactDOM.render(<OptionsMenu />, rootElement);

注意:this.dropdownBoxRef.current.contains(event.target) 行是游戏规则的改变者。

关于javascript - 如何引用组件并监听外部点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073577/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com