reactjs - 无法有条件地为下拉菜单工作
问题描述
我正在尝试使用 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,
});
}
};
解决方案
this is what i found works for me
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);
});
}
}
推荐阅读
- java - 试图纠正怀孕这个词
- promise - Angular7 Promise 无法使用
- c# - C# 类 linq 扩展
- c++ - 使用 OpenSSL 内存 BIO 进行第二次 ClientHello 后验证方法未触发
- oracle - 如何循环遍历 PLSQL 中的游标?
- xamarin - 如何在 xamarin UWP 中使用字体
- c - 如何将 uint8_t 从 uart_read_bytes 转换为 char 或可以添加到 cJSON 对象的东西?
- atom-editor - 如何在原子编辑器上将未保存文件的初始单词显示为标题而不是“无标题”
- automation - 如何通过 PuTTY 连接远程服务器并执行本地和远程文件
- r - 与 R shinyApp 的本地服务器端口连接