单击文档时如何关闭菜单(EventListener)

时间:2018-10-24 23:06:50

标签: javascript reactjs

我一直在尝试向文档中添加 EventListener 来关闭菜单,但是event.stopPropagation()似乎都没有;真的听我说://有人可以帮我吗?请

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import "./header.css";

class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {
            language : "en"
        }
    }

    openMenu = () => {
        let menuPaths = document.getElementById('menu');
        let hideAnimation = () => {
            menuPaths.classList.remove('animate-left');
            menuPaths.classList.add('animate-right');
        }
        let showAnimation = () => {
            menuPaths.classList.remove('animate-right');
            menuPaths.classList.add('animate-left');
        }
        menuPaths.classList.toggle('show');
        if(menuPaths.classList.contains('show')) {
            showAnimation();
        } else {
            hideAnimation();
        }
    } 

    render() {
        //user logged in? render nav. Else, render login/signup
        const userAction = (
            <div className='header_action'>
                <button className='header_action_signup orange-md-btn'>SIGN UP</button>
                <button className='header_action_login orange-md-btn'>LOGIN</button>
            </div>
        )

        return (
            <div className='header'>
                <div className="header_menu">
                    <img onClick={event => {
                        event.stopPropagation();
                        return this.openMenu(event);
                    }} src={require("./pictures/hamburger_menu.svg")}/>
                </div>
                <div className='header_paths' id="menu">
                    <NavLink to='/index/acceuil'>Home</NavLink>
                    <NavLink to='/index/how'>How does it work</NavLink>
                    <a href= {BLOG_URL + '/'+ this.state.language +'/'}>Blog</a>
                    <a href={BLOG_URL + '/media/'}>Media</a>
                    <NavLink to='/index/contact'>Contact Us</NavLink>
                    <a href={PUBLIC_MARKETPLACE}>Marketplace</a>
                    <a href="#">Fr</a>
                </div>
                <NavLink to='/index/acceuil' className='header_logo' >
                    <img src={require("./pictures/logo_march2.png")}/>
                </NavLink>
                {userAction}
            </div>
        )
    }
}

export default Header;

这就是我尝试在openMenu函数中添加的内容

document.addEventListener("click", function(event) {
            event.stopPropagation();
            document.removeEventListener("click", this.hideAnimation());
})

我还尝试了在componentDidMount上单击时附加removeEventHandler,该操作无效,并且我尝试了event.preventDefault();的多种组合。我在使用jQuery之前就掌握了它,但是现在我必须使用react,所以我不想与jQuery混合使用。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

  1. 首先,您需要使用状态切换菜单,但不能直接更改DOM。
  2. 据我所知,您想在菜单外单击以关闭菜单。如果是这样,您可能想使用react-onclickoutside并创建handleClickOutside函数并将其传递给HOC。