在打开React.bootstrap Navbar下拉菜单时,我要防止主体滚动

时间:2019-04-08 15:10:07

标签: reactjs navbar react-bootstrap bodyscrolllock

我正在使用react-bootstrap中的Navbar和Nav。当我单击汉堡包时,我想防止下拉菜单打开时主体滚动。

我尝试使用body-scroll-lock,但是很难发现要在Navbar组件中将哪个元素设置为targetElement以及在何处调用showtargetElement和hideTargetElement函数。

import React, { Component } from 'react';
import { Navbar, Nav } from 'react-bootstrap';
import { disableBodyScroll, enableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock';


class Header extends Component {
  targetElement = null;

  componentDidMount() {
    this.targetElement = document.querySelector('.menu');
  }

  showTargetElement = () => {
    if('.menu') {
      disableBodyScroll(this.targetElement);
    }
  }

  hideTargetElement = () => {
    enableBodyScroll(this.targetElement);
  }

  componentWillUnmount() {
    clearAllBodyScrollLocks();
  }

  render() {
    return (
      <div className="header">
        <Navbar className="my-navbar" variant="dark" expand="lg">
          <Navbar.Brand className="my-brand" href="#home">Karina Gaulin</Navbar.Brand>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse
            className="dropdown"
            id="basic-navbar-nav"
          >
            <Nav className="mr-auto menu">
              <Nav.Link href="#home">Home</Nav.Link>
              <Nav.Link href="https://www.resume.com/share/karinagaulin" download>Resume</Nav.Link>
              <Nav.Link href="mailto:karinagaulin@gmail.com">Connect</Nav.Link>
            </Nav>
          </Navbar.Collapse>
        </Navbar>
      </div>
      );
    }
  }

  export default Header;

0 个答案:

没有答案