关闭响应式导航|反应JS

时间:2018-01-08 15:17:34

标签: javascript reactjs

我有一个标题组件来管理导航组件的状态。

如果用户点击汉堡图标,导航会成功切换,但是,如果用户点击或点击导航之外的任何位置,我需要导航关闭。

我怎样才能做到这一点?

这是我的代码:

export default class Header extends React.Component {

    constructor() {
        super();

        this.state = {
            mobileOpenNav: false
        };

        bindAll([
            'openMobileNav',
            'openContactModal'
        ],this);
    }

    openMobileNav() {
        this.props.contactModalToggle(false);

        this.setState({
            mobileOpenNav: !this.state.mobileOpenNav
        })
    }



    openContactModal() {
        this.props.contactModalToggle();

        this.setState({
            mobileOpenNav: !this.state.mobileOpenNav
        });
    }

    render() {
        const {nav, contactModalToggle, location, logos} = this.props;
        const {mobileOpenNav} = this.state;

        return (
            <div className="header-wrap">
                <div className="header">
                    <Logo location={location} logoUrls={logos} />
                    <Navigation 
                        location={location} 
                        nav={nav} 
                        contactModalToggle={this.openContactModal} 
                        mobileOpen={mobileOpenNav} 
                        mobileToggle={this.openMobileNav} 
                    />
                    <div className="hamburger" onClick={this.openMobileNav}><img src={HamburgerIcon} /></div>
                </div>
            </div>
        )
    }
}

2 个答案:

答案 0 :(得分:1)

以下解决方案适合您。

componentDidMount() { 
     document.addEventListener('click', this.handleClickOutside.bind(this), true); 
} 

componentWillUnmount() { 
    document.removeEventListner('click', this.handleClickOutside.bind(this), true); 
} 

handleClickOutside(e) { 
    const domNode = ReactDOM.findDOMNode(this); 

    if(!domNode || !domNode.contains(event.target)) { 
       this.setState({ 
         mobileOpenNav: false 
       }); 
    } 
 }

答案 1 :(得分:0)

使用react-onclickoutside模块https://github.com/Pomax/react-onclickoutside

import onClickOutside from "react-onclickoutside"
import Navigation from "pathToNvaigation"

const ContentWrapper = onClickOutside(Navigation)

并使用

<ContentWrapper
  location={location} 
  nav={nav} 
  contactModalToggle={this.openContactModal} 
  mobileOpen={mobileOpenNav} 
  mobileToggle={this.openMobileNav}  
/>