假设我们有以下几个页面:

  • 首页:/
  • 文章列表页:/articles
  • 文章详情页:/articles/:id
  • 关于页:/about

我们可以使用'react-router-dom'库来制作导航条,具体步骤如下:

  1. 安装'react-router-dom'库:npm install react-router-dom
  2. 在'App.js'中引入'BrowserRouter'和'Link'组件:
import { BrowserRouter, Link } from 'react-router-dom';
  1. 使用'BrowserRouter'包裹整个应用,并在其中添加导航条:
function App() {
  return (
    <BrowserRouter>
      <nav>
        <ul>
          <li><Link to='/'>首页</Link></li>
          <li><Link to='/articles'>文章列表</Link></li>
          <li><Link to='/about'>关于</Link></li>
        </ul>
      </nav>
      <Switch>
        <Route exact path='/' component={Home} />
        <Route exact path='/articles' component={Articles} />
        <Route path='/articles/:id' component={ArticleDetail} />
        <Route exact path='/about' component={About} />
        <Route component={NotFound} />
      </Switch>
    </BrowserRouter>
  );
}
  1. 在导航条中使用'Link'组件来跳转到对应的页面。注意,在'/articles'页面中可能有多篇文章,因此需要在'/articles/:id'中使用动态路由来获取每篇文章的ID:
function Articles() {
  return (
    <div>
      <h2>文章列表</h2>
      <ul>
        <li><Link to='/articles/1'>文章1</Link></li>
        <li><Link to='/articles/2'>文章2</Link></li>
        <li><Link to='/articles/3'>文章3</Link></li>
      </ul>
    </div>
  );
}

function ArticleDetail(props) {
  const articleId = props.match.params.id;
  // 根据文章ID获取文章详情
  return (
    <div>
      <h2>文章详情</h2>
      <p>文章ID:{articleId}</p>
      {/* 显示文章内容 */}
    </div>
  );
}

这样就可以制作出一个简单的导航条了。当用户点击导航条中的链接时,页面会根据对应的路由进行跳转。同时,'BrowserRouter'组件会监听URL的变化,当URL发生变化时会自动更新页面内容。


原文地址: https://www.cveoy.top/t/topic/ngkT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录