我正在使用React JS构建菜单栏。单击菜单项时,应打开相应的megamenu。在megamenu外部单击时,它应自行关闭。我通过切换megamenu的状态来做到这一点。但是我也想在第二次单击菜单项时关闭megamenu(即通过单击menu-item来切换megamenu的关闭和打开)。我被困在这里,第二次单击菜单项时,状态没有切换回去。

class Menubar extends React.Component {
  constructor() {
    super();
    this.state = {
      clicked: false
    };
    this.handleClick = this.handleClick.bind(this);
    this.handleOutsideClick = this.handleOutsideClick.bind(this);
  }

  componentWillMount() {
    document.addEventListener('click', this.handleOutsideClick, false);
  }

  componentWillUnmount(){
    document.removeEventListener('click', this.handleOutsideClick, false);
  }

  handleClick() {
    this.setState({clicked: !this.state.clicked});
  }

  handleOutsideClick(){
    if (this.refs.megaMenu.contains(event.target)) {
      } else {
        this.setState({
          clicked: false
        });
      }
   }

   render() {
    return (
      <div className="container">
        <div className="menu-bar">
          {/* Menu*/}
          <div className="menu-bar-item">
            <a className="menu-bar-link" href="#" onClick={this.handleClick}>Points</a>
            <div className={"mega-menu"+" "+this.state.clicked} ref="megaMenu">
              <div className="mega-menu-content">
                <p>Points Menu</p>
              </div>
            </div>
          </div>
        </div>
      </div>
     );
   }
}

ReactDOM.render(
  <Menubar />,
  document.getElementById('example')
);


Codepen Demo

最佳答案

您需要移动ref="megaMenu",使其也包含按钮,否则,单击按钮时也会触发handleOutsideClick,并且将this.state.clicked翻转两次。另外,您忘记了在event处理程序中传递handleOutsideClick

class Menubar extends React.Component {
  constructor() {
    super();
    this.state = {
      clicked: false
    };
    this.handleClick = this.handleClick.bind(this);
    this.handleOutsideClick = this.handleOutsideClick.bind(this);
  }

  componentWillMount() {
    document.addEventListener('click', this.handleOutsideClick, false);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleOutsideClick, false);
  }

  handleClick() {
    this.setState({clicked: !this.state.clicked});
  }

  handleOutsideClick(event) {
    if (!this.menu.contains(event.target)) {
      this.setState({
        clicked: false
      });
    }
  }

  render() {
    return (
      <div className="container">
        <div className="menu-bar">

          {/* Menu*/}
          <div className="menu-bar-item" ref={el => this.menu = el}>
            <a className="menu-bar-link" href="#" onClick={this.handleClick}>Points</a>
            <div className={"mega-menu" + " " + this.state.clicked}>
              <div className="mega-menu-content">
                <p>Points Menu</p>
              </div>
            </div>
          </div>

        </div>
      </div>
    );
  }
}

ReactDOM.render(
  <Menubar />,
  document.getElementById('example')
);


我已经修复了您的Codepen Demo

另外,请考虑使用ref={el => this.menu = el}之类的回调引用
这是一种更好的方法。

10-06 05:15