问题描述
我正在制作一个网站,我在其中使用 react-router-dom 的 NavLink 组件来防止单页应用程序体验的重新渲染.
I'm making a website where I'm using react-router-dom's NavLink components to prevent rerenders for a single page application experience.
当我试图使站点具有响应性时,我一直在尝试使响应式导航栏在选择 NavLink 后从 react-bootstrap 折叠,但 collapseOnSelect 行为似乎不适用于 Nav.Link 以外的任何其他内容react-bootstrap 自带的组件.
As I am trying to make the site responsive, I have been trying to make the responsive navbar from react-bootstrap collapse after selecting a NavLink, but the collapseOnSelect behaviour doesn't seem to work for anything other than the Nav.Link components that come with react-bootstrap.
其他解决方案建议使用手动切换功能等将道具传递给导航 (navExpanded:true),但这似乎仍会由于状态更改而强制重新渲染.我想避免这种情况的主要原因是我使用 react-transitions-group 在页面之间进行了转换.
Other solutions have recommended passing down props to the nav (navExpanded:true) with manual toggle functions etc, but this seems to still force a rerender due to the state change. The main reason I want to avoid this is because I have made transitions between pages using react-transitions-group.
<Navbar collapseOnSelect expand="md" variant="dark">
<Container>
<Navbar.Brand href="/"><Logo/></Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="Navs ml-auto">
<NavLink className="nav-link" to="/about">ABOUT</NavLink>
<NavLink className="nav-link" to="/portfolio">PORTFOLIO</NavLink>
<NavLink className="nav-link" to="/contact">CONTACT</NavLink>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
任何帮助将不胜感激!
推荐答案
我有同样的问题,我使用来自 'react-bootstrap' 的 Nav.Link 作为来自 'react-router-dom' 的链接,不要忘记添加 href 属性.在此示例中,除比萨饼链接之外的所有链接都会折叠导航栏.希望对你有帮助.
I have the same problem, i use the Nav.Link from 'react-bootstrap' as Link from 'react-router-dom', don't forget to add the href attribut.In this example all links except pizzas link collapse the nav bar.Hope it's Help You.
import React from 'react';
import { Navbar, Nav } from 'react-bootstrap';
import NavBrand from './NavBrand/NavBrand';
import { Link } from 'react-router-dom';
const Navigation = ({ brand }) => {
return (
<Navbar collapseOnSelect expand='sm' bg='dark' variant='dark' fixed='top'>
<NavBrand text={brand.text} />
<Navbar.Toggle aria-controls='responsive-navbar-nav' />
<Navbar.Collapse id='responsive-navbar-nav'>
<Nav className='mr-auto'>
<Nav.Link as={Link} to='/assiettes' href='/assiettes'>
ASSIETTES
</Nav.Link>
<Nav.Link as={Link} to='/pizzas'>
PIZZAS
</Nav.Link>
<Nav.Link as={Link} to='/sandwichs' href='/sandwichs'>
SANDWICHS
</Nav.Link>
<Nav.Link as={Link} to='/tacos' href='/tacos'>
TACOS
</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
);
};
export default Navigation;
这篇关于带有 react-router-dom NavLinks 的 react-bootstrap 导航栏中的 collapseOnSelect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!