gpt4 book ai didi

reactjs - 事件 NavLink 到父元素

转载 作者:行者123 更新时间:2023-12-03 13:11:57 27 4
gpt4 key购买 nike

我正在使用 React Router v4,并且我有一个情况,在我的导航链接上,我想为 NavLink 父元素启用 active className,而不是NavLink 本身。

即使我不在 Switch 元素内,是否有办法访问路径(match)?

或者我必须保持状态吗?因为我觉得它有点缺少路由器的想法。

这是我的示例,我想将 active className 应用到 li 元素而不是 NavLink:

const {
HashRouter,
Switch,
Route,
Link,
NavLink,
} = ReactRouterDOM

const About = () => (
<article>
My name is Moshe and I'm learning React and React Router v4.
</article>
);

const Page = () => (
<Switch>
<Route exact path='/' render={() => <h1>Welcome!</h1>} />
<Route path='/about' component={About}/>
</Switch>
);

const Nav = () => (
<nav>
<ul>
<li><NavLink exact to="/">Home</NavLink></li>
<li><NavLink to="/about">About</NavLink></li>
</ul>
</nav>
);

class App extends React.Component {
render() {
return (
<div>
<Nav />
<Page />
</div>
);
}
}
ReactDOM.render((
<HashRouter>
<App />
</HashRouter>),
document.querySelector("#app"));

https://codepen.io/moshem/pen/ypzmQX

最佳答案

看来这个目标不是很容易实现。我使用 react router docs 中描述的 withRouter HOC 。它允许从位于 Routes 之外的组件内部的 props 访问 { match, location, History }。在示例中,我包装了 Nav 组件来获取location 及其pathname。下面是示例代码:

class Nav extends React.Component {
getNavLinkClass = (path) => {
return this.props.location.pathname === path ? 'active' : '';
}
render() {
return (
<nav>
<ul>
<li className={this.getNavLinkClass("/")}><NavLink exact to="/">Home</NavLink></li>
<li className={this.getNavLinkClass("/about")}><NavLink to="/about">About</NavLink></li>
</ul>
</nav>
)};
}
Nav = withRouter(Nav);

您可能需要注意路由中的params(如果有的话),才能正确匹配。但是您仍然必须匹配 NavLink 中的每个路径,这可能不是漂亮的代码。但其想法是,当路线更改时,Nav 会重新渲染,并突出显示正确的li

这是 codesandbox 上的一个工作示例.

关于reactjs - 事件 NavLink 到父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com