首页 文章

具有2个入口点的React路由器

提问于
浏览
2

我正在尝试实现开发人员使用react创建新页面的能力,同时保持兼容性以及我们用于所有页面的母版页模板(包括过滤器,选项卡等)

我需要的是能够将导航组件渲染为1 div,页面内容(App)呈现为另一个(如下图所示)

enter image description here

我目前的解决方案涉及单独渲染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 回答

  • 1

    要创建两个不同的应用程序并共享相同的历史记录对象,您需要手动创建路由器并提供您想要使用的历史记录对象类型 . BrowserRouter和HashRouter都为您完成此操作(因此名称为Browser和Hash路由器) . 但您可以使用Router并为其提供历史对象 .

    // 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'));
    

相关问题