2017-10-18 34 views
2

我試圖實現開發人員使用react創建新頁面的能力,同時保持兼容性,以與我們用於所有頁面的主頁面模板(包括過濾器,選項卡等)一起工作具有2個入口點的React路由器

我需要是

enter image description here

我的當前解決方案包括被渲染成另一種來呈現導航組件到1個格的能力,與頁面內容(應用程序)(下面示出)分別呈現2個部件,但我在掙扎的地方是如何橋接路由器 他們倆。我遇到了路由器有2個實例的問題(我會從代碼中理解爲什麼),但我不確定如何構造這個實現我想要的行爲。

我如何能夠將這些組件渲染爲2個獨立的根div,但是仍然共享歷史記錄和導航路徑更改會反映到應用程序組件中?

import React } from 'react'; 
import { render } from 'react-dom'; 
import { BrowserRouter, Link, Route, Switch } from 'react-router-dom'; 
import ContactPage from './ContactPage'; 

const HomePage =() => <div> Home page </div>; 
const AboutPage =() => <div> This is an About Page </div>; 

const Navigation =() => (
    <div> 
     {/* Match structure of legacy tab structure, we then just replace current with a react component for navigation */} 
     <li className="dropdown" id="tab-menu-li"> 
      <ul className="nav nav-tabs" id="tab-menu-list"> 
       <li className="text-left"> 
        <Link to={`/home`}>home</Link> 
       </li> 
       <li className="text-left"> 
        <Link to={`/about`}>Contact Us</Link> 
       </li> 
      </ul> 
     </li> 
     {/* Renders into tab-menu-li fine if I put the switch in here 
     <Switch> 
      <Route path={`/home`} exact component={HomePage} /> 
      <Route path={`/about`} exact component={ContactPage} /> 
     </Switch> 
     */} 
    </div> 
); 

const App =() => (
    <Switch> 
     {/* How can I make this App component, catch the route changes from navigation? 
      This component draws fine, and /contact etc will work on page load. But any route changes triggered in navigation are never reflected here 
     */} 
     <Route path={`/home`} exact component={HomePage} /> 
     <Route path={`/about`} exact component={AboutPage} /> 
    </Switch> 
); 

render(<BrowserRouter><Navigation /></BrowserRouter>, document.getElementById('tab-menu-li')); 
render(<BrowserRouter><BaseLayout /></BrowserRouter>, document.getElementById('dataContainer')); 

回答

1

要在兩個不同的應用程序和共享您需要手動創建路由器,並提供歷史記錄對象那種你想使用相同的歷史對象。 BrowserRouter和HashRouter都是爲你做的(因此名稱爲Browser和Hash路由器)。但是你可以使用路由器併爲它提供一個歷史對象。

// history.js 
import { createBrowserHistory } from 'history' 

const browserHistory = createBrowserHistory({ 
    /* pass a configuration object here if needed */ 
}); 

render(<Router history={browserHistory}><Navigation /></Router>, document.getElementById('tab-menu-li')); 
render(<Router history={browserHistory}><BaseLayout /></Router>, document.getElementById('dataContainer')); 
+0

太棒了,這就是我所追求的魅力,謝謝! –