【问题标题】:Is it possible to access the current route component with React Router是否可以使用 React Router 访问当前路由组件
【发布时间】:2015-12-04 07:17:15
【问题描述】:

例如,我有如下路线:

<Route path="about" component={AboutPage} />
<Route path="status" component={StatusPage} />

假设当前路由是'#/about'。我需要routerInstance.currentComponent 之类的东西来返回AboutPage 组件实例。

React Router 有方法吗?

ps。我知道从外部访问组件实例不是 React 做事的方式,但我仍然需要它。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    不确定 react-router 是否已经公开了它,有一个旧的 GitHub 讨论未记录的 api,here 但您可以根据路由自行设置。

    //AboutPage
    componentDidMount() {
      global.currentComponent  = this
    }
    
    //StatusPage
    componentDidMount() {
      global.currentComponent  = this
    }
    

    【讨论】:

    • 当然,这正是我现在正在做的,但我希望有一些内置的方法。
    • 只是查看了路由器组件源,它看起来并没有暴露你需要的东西
    • 看看这个 github issue 暴露的 api
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2017-04-24
    • 2017-06-12
    • 1970-01-01
    • 2021-02-11
    • 2022-07-27
    • 2018-12-13
    相关资源
    最近更新 更多