首页 > 解决方案 > 反应路线不适用于自定义导航栏

问题描述

我正在使用在 NPM 上找到的自定义导航栏库来呈现我的导航栏,但是navlinks自定义导航栏中的导航栏不起作用。当我单击链接时,地址栏中的路由会更新,但不会呈现组件。虽然使用简单列表时,我能够渲染所有路线。

要复制的 CodeSandbox 示例

function App() {

return (
    <React.Fragment>
        /* This custom navbar is not working for routing */
        <Navbar></Navbar>

        /* This list is working fine for routing */
        {/* <ul>
            <li>
                <NavLink to='/'>Home</NavLink>
            </li>
            <li>
                <NavLink to='/about'>About</NavLink>
            </li>
            <li>
                <NavLink to='/contact'>Contact</NavLink>
            </li>
        </ul> */}

        <Switch>
            <Route exact path='/' component={Home} />
            <Route path='/about' component={About} />
            <Route path='/contact' component={Contact} />
        </Switch>
    </React.Fragment>
  );
}

这是我正在使用的自定义导航栏组件:自定义导航栏

标签: reactjsreact-routernavbarreact-router-dom

解决方案


您可能会忘记用 <Router> or <BrowserRouter>.

试一下:

import {BrowserRouter, Router} from "react-router-dom";

 <BrowserRouter>
            <React.Fragment>
                ...
            </React.Fragment>
  </BrowserRouter>

或者

<Router>
            <React.Fragment>
                ...
            </React.Fragment>
</Router>

推荐阅读