<Nav pullRight activeKey={1}>
<NavItem eventKey={1} href="#" active>技术秘籍</NavItem>
<NavItem eventKey={2}>生活点滴</NavItem>
<NavItem eventKey={3} href="#">休闲娱乐</NavItem>
<NavItem eventKey={4} href="#">沟通交流</NavItem>
<NavItem eventKey={5} href="#">关于博主</NavItem>
</Nav>
我希望第一个项目在初始时处于活动状态,但是活动没有做任何事情,有人知道为什么吗
您还通过在第一个 NavItem 上指定“活动”来覆盖您的 activeKey 值。
有效地设置“activeKey={1}”就是实现你所要求的。然而,这也意味着你将你的道具硬连线到 1,所以它永远不会改变。
可能你真正想要的是包括本地状态的东西,即:
const Navigation = React.createClass({
getInitialState() {
return {activeKey: 1};
},
handleSelect(selectedKey) {
this.setState({activeKey: selectedKey});
},
render() {
return (
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
<a className="page-scroll" href="#page-top" onClick={this.handleSelect.bind(null, 0)}>Some Brand</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav bsStyle="pills" activeKey={this.state.activeKey} onSelect={this.handleSelect}>
<NavItem eventKey={1} href="#">Link</NavItem>
<NavItem eventKey={2} href="#">Link</NavItem>
<NavItem eventKey={3} href="#">Link</NavItem>
<NavItem eventKey={4} href="#">Link</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
});
我把 navbrand 也放在那里,以展示如何使用特定值绑定点击处理程序(即 0 表示中性 - 不突出显示)。
首先,从 react-router-dom 导入 useLocation 在你的类中,但在你的 return 或 render 语句之前,设置一个等于 useLocation() 的变量(我只是在我的代码中将它命名为 location)
在您的导航菜单链接中,您想添加 eventKey="您的相对路径" 在导航声明中,添加 activeKey={location.pathname}
这也适用于 navdropdown。我正在使用 react-bootstrap 组件(NavBar、Nav、Nav.Link、NavDropDown)