首页 > 解决方案 > 无法有条件地为下拉菜单工作

问题描述

我正在尝试使用 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,
      });
    }
};

标签: reactjsdropdown

解决方案


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);
  });  

}

}


推荐阅读