我正在尝试获取一个下拉列表以与React一起显示,但是当前的这套代码存在问题。它应该在单击菜单按钮时以及在目标外部单击时隐藏菜单。我在做什么错?
constructor(){
super()
this.container = React.createRef();
this.state = state;
let state = {
open: false,
};
}
handleButtonClick = () => {
this.setState(state => {
return {
open: !state.open,
};
});
};
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,
});
}
};
这是我发现对我有用的constructor(){super();
this.state = {
showMenu: false,
};
this.showMenu = this.showMenu.bind(this);
this.closeMenu = this.closeMenu.bind(this);
}
showMenu(event){event.preventDefault();
this.setState({ showMenu: true }, () => {
document.addEventListener('click', this.closeMenu);
});
}
closeMenu(event){
if (!this.dropdownMenu.contains(event.target)) {
this.setState({ showMenu: false }, () => {
document.removeEventListener('click', this.closeMenu);
});
}
}