求助:选中react-bootstrap NavDropdown子MenuItem时,父项未激活
这个问题我太熟悉了!当使用react-bootstrap的NavDropdown结合react-router时,父级下拉菜单默认不会根据子路由的激活状态自动标记自己为激活——它只会检查自身的eventKey和当前路由是否匹配,不会关联子项的路径,所以你跳转到/users或/users/add时,Manage User始终不会变成激活状态。
下面给你两种实用的解决方法:
方案1:通过withRouter和isActive手动判断(类组件适用)
我们可以借助react-router的withRouter高阶组件获取当前路由的location对象,然后判断路径是否包含/users,再把这个判断结果传给NavDropdown的isActive属性,强制标记它为激活状态。
import { withRouter } from 'react-router-dom'; import { NavDropdown, MenuItem } from 'react-bootstrap'; import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap'; class YourNavigationComponent extends Component { render() { const { location } = this.props; // 判断当前路由是否以/users开头,覆盖所有子路由场景 const isDropdownActive = location.pathname.startsWith('/users'); return ( <NavDropdown eventKey={4} title="Manage User" id="basic-nav-dropdown" isActive={isDropdownActive} // 这里传入激活状态判断结果 > <LinkContainer to="/users/add"> <MenuItem eventKey={4.1}>Add User</MenuItem> </LinkContainer> <IndexLinkContainer to="/users"> <MenuItem eventKey={4.2}>View User</MenuItem> </IndexLinkContainer> </NavDropdown> ); } } // 用withRouter包裹组件,注入location属性 export default withRouter(YourNavigationComponent);
方案2:使用useLocation钩子(函数组件适用)
如果你的组件是函数式的,直接用react-router的useLocation钩子获取当前路由信息就行,逻辑和类组件一致:
import { useLocation } from 'react-router-dom'; import { NavDropdown, MenuItem } from 'react-bootstrap'; import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap'; function YourNavigationComponent() { const location = useLocation(); const isDropdownActive = location.pathname.startsWith('/users'); return ( <NavDropdown eventKey={4} title="Manage User" id="basic-nav-dropdown" isActive={isDropdownActive} > <LinkContainer to="/users/add"> <MenuItem eventKey={4.1}>Add User</MenuItem> </LinkContainer> <IndexLinkContainer to="/users"> <MenuItem eventKey={4.2}>View User</MenuItem> </IndexLinkContainer> </NavDropdown> ); } export default YourNavigationComponent;
补充说明
startsWith('/users')可以覆盖所有以/users开头的子路由,包括/users/add、/users/:id/edit这些你配置的路径,不用逐个判断。- 确保你已经正确安装并导入了
react-router-bootstrap的相关组件(你代码里已经用了LinkContainer和IndexLinkContainer,这部分应该没问题)。
内容的提问来源于stack exchange,提问作者Asif Iqbal
相关产品推荐
相关产品推荐

