使用这个https://codedaily.io/tutorials/Create-a-Dropdown-in-React-that-Closes-When-the-Body-is-Clicked我找到了我的解决方案,让我的下拉菜单在点击时关闭外面的任何地方。
但问题是,我有两个相似的下拉组件来获得这个应用,所以当我应用我的最后一个下拉菜单时,我的最后一个下拉菜单工作正常,但不是第一个。我不明白为什么?谁能帮我解决这个问题。
this.container = React.createRef();
this.state = {
open: false,
};
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = (event) => {
if (
this.container.current &&
!this.container.current.contains(event.target)
) {
this.setState({
open: false,
});
}
};
在我的身体 div 处,
<div className="container" ref={this.container}>
{this.state.open && <div>mydropdown1</div>}
</div>
<div className="container" ref={this.container}>
{this.state.open && <div>mydropdown2</div>}
</div>
或者我可以使用 react-foco 吗?