1

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

我曾尝试使用 body-scroll-lock 但很难发现将哪个元素设置为 targetElement 以及在哪里调用 Navbar 组件中的 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;
4

0 回答 0