从 Route 组件外部路由

Routing from outside of a Route component

我有一个正在使用 React 路由器的应用程序,但我不知道如何在此用例中更改路由。以下是我的代码的结构:

import { BrowserRouter as Router, Route, Link } from "react-router-dom";
<Router>
    <Panels />
    <Route path="/view" render={()=> <MyComponent />} />
    <Route path="/about" render={()=> <MyOtherComponent />} />
</Router>

<Panels> 内有一些我想要更改路线的选项卡。

<Tabs defaultActiveKey="1" onChange={}> 
    <TabPane tab="Tab 1" key="1" > 
       <Somecomponent /> 
    </TabPane> 
    <TabPane tab="Tab 2" key="2"> 
      Test me 
    </TabPane>
  </Tabs> 

这些是 antd 标签,所以它们没有我可以将 <Link> 放入的可点击组件,并且 <Panels><Route> 之外,所以我不是确定我是否能够以其他方式访问历史对象。我可以将面板放在每个 <Route> 中,但这真的很糟糕。

我应该怎么做?

终于想通了。

import { withRouter } from 'react-router-dom'
...
<Tabs defaultActiveKey="1" onChange={(key)=> this.props.history.push(`/${key}`)}> 
    <TabPane tab="Tab 1" key="1" > 
       <Somecomponent /> 
    </TabPane> 
    <TabPane tab="Tab 2" key="2"> 
      Test me 
    </TabPane>
</Tabs> 
...
export default withRouter(Panels);

withRouter 包装导出,使组件能够访问历史对象以推送和读取路由。我最初看到了这个解决方案,但无法让它发挥作用。结果是因为我从 react-router 而不是 react-router-dom 导入 withRouter,所以我加载了错误的历史记录。