当我在react中点击一个链接时,如何强制bootstrap offcanvas navbar关闭?

ymzxtsji  于 2022-12-08  发布在  Bootstrap
关注(0)|答案(1)|浏览(135)

我有一个react应用程序,当我点击汉堡包时,它会从右侧进入 Bootstrap offcanvas导航栏。当我点击offcanvas元素外部或组件内部的x时,它会工作并关闭,但当我点击链接时,它会呈现新页面,但导航栏仍然打开。有没有办法在用户点击新页面的链接时强制它关闭?
下面是导入到App.js的头中的导航条代码:

import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import { LinkContainer } from 'react-router-bootstrap';
import Offcanvas from 'react-bootstrap/Offcanvas';

function OffcanvasNav() {
  return (
    <>
      {[false].map((expand) => (
        <Navbar key={expand} bg='light' expand={expand} className='mb-3'>
          <Container fluid>
            <Navbar.Brand to='/'>Denver Judo</Navbar.Brand>
            <Navbar.Toggle aria-controls={`offcanvasNavbar-expand-${expand}`} />
            <Navbar.Offcanvas
              id={`offcanvasNavbar-expand-${expand}`}
              aria-labelledby={`offcanvasNavbarLabel-expand-${expand}`}
              placement='end'
            >
              <Offcanvas.Header closeButton>
                <Offcanvas.Title id={`offcanvasNavbarLabel-expand-${expand}`}>
                  Denver Judo
                </Offcanvas.Title>
              </Offcanvas.Header>
              <Offcanvas.Body>
                <Nav className='justify-content-end flex-grow-1 pe-3'>
                  <LinkContainer to='/'>
                    <Nav.Link>Home</Nav.Link>
                  </LinkContainer>
                  <LinkContainer to='/schedule'>
                    <Nav.Link>Schedule</Nav.Link>
                  </LinkContainer>
                  <LinkContainer to='/about'>
                    <Nav.Link>About</Nav.Link>
                  </LinkContainer>
                </Nav>
              </Offcanvas.Body>
            </Navbar.Offcanvas>
          </Container>
        </Navbar>
      ))}
    </>
  );
}

export default OffcanvasNav;
vzgqcmou

vzgqcmou1#

我不知道这是否是处理它的最佳方式,但我向每个LinkContainers添加了一个onClick来设置expend = '',它工作了。

<LinkContainer to='/' onClick={() => (this.expand = '')}>
  <Nav.Link>Home</Nav.Link>
</LinkContainer>
<LinkContainer to='/schedule' onClick={() => (this.expand = '')}>
  <Nav.Link>Schedule</Nav.Link>
</LinkContainer>
<LinkContainer to='/about' onClick={() => (this.expand = '')}>
  <Nav.Link>About</Nav.Link>
</LinkContainer>

相关问题