gpt4 book ai didi

javascript - 在 ReactJs 中使用 react-router 获取事件路由

转载 作者:可可西里 更新时间:2023-11-01 02:20:18 24 4
gpt4 key购买 nike

我正在使用 reactjs 创建一个项目。在我的应用程序中,我正在使用这个获取事件路由:

this.context.router.isActive

但是变得不确定,我正在使用 react-router 4。早些时候,当我使用较低版本的 react-router 时,这对我有用。这是我的代码:

class NavLink extends React.Component {

render() {


console.log( this.context.router.isActive)
let isActive = this.context.router.isActive(this.props.to, true);
let className = isActive ? "active" : "";
return(
<li className={className} {...this.props}>
<Link {...this.props}/>
</li >
);
}
}

NavLink.contextTypes = {
router: PropTypes.object
};

最佳答案

架构在 react-router v4 和 this.context.router.isActive 中发生了变化不再受支持。

在 react-router-v4 中,您可以使用公开的 NavLink 而不是自己创建 NavLink。零件。

From the documentation:

NavLink

A special version of the that will add styling attributes to the rendered element when it matches the current URL.

import { NavLink } from 'react-router-dom'

<NavLink to="/about">About</NavLink>

它还为您提供了一个 activeClassName Prop :

activeClassName: string

The class to give the element when it is active. The default given class is active. This will be joined with the className prop.

<NavLink
to="/faq"
activeClassName="selected"
>FAQs</NavLink>

为什么不支持 this.context.router.isActive:

这是来自 github 的摘录问题

渲染 <Route>不一定意味着“仅在匹配当前位置时呈现”。例如,它可以用于将上下文中的路由器变量作为 props 注入(inject)到组件中。

<NavLink> , <Route>正在使用 children 属性,这意味着无论路由是否匹配,它都会调用 children 函数。如果匹配为空,则我们知道它不匹配。

如果您不想使用 <Route children>通过这种方式,React Router 提供了一种命令式方法 matchPath功能。这就是<Switch>es<Route>s在内部使用以将位置与路径匹配。

如果您的组件没有收到 Router Prop ,然后你可以使用 withRouter 注入(inject)它高级组织

import { withRouter } from 'react-router';

export class withRouter(MyComponent);

关于javascript - 在 ReactJs 中使用 react-router 获取事件路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47693540/

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