📅  最后修改于: 2023-12-03 14:46:59.853000             🧑  作者: Mango
react-router-dom
是一个用于构建 React 应用程序中页面导航和路由功能的库。它基于 React Router 核心库并提供了针对浏览器环境的常用功能。react-router-dom
提供了一组易于使用且灵活的组件,可帮助开发人员快速实现路由功能。
使用 npm 安装 react-router-dom
:
npm install react-router-dom
import React from 'react';
import { BrowserRouter, Route, Switch, NavLink } from 'react-router-dom';
const Home = () => (
<div>
<h1>Home</h1>
<p>Welcome to the home page!</p>
</div>
);
const About = () => (
<div>
<h1>About</h1>
<p>This is the about page.</p>
</div>
);
const NotFound = () => (
<div>
<h1>404 Not Found</h1>
<p>The requested page could not be found.</p>
</div>
);
const App = () => (
<BrowserRouter>
<div>
<nav>
<ul>
<li>
<NavLink exact to="/">Home</NavLink>
</li>
<li>
<NavLink to="/about">About</NavLink>
</li>
</ul>
</nav>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</div>
</BrowserRouter>
);
export default App;
可以通过使用路由的 props
来获取传递的参数:
import React from 'react';
import { useParams } from 'react-router-dom';
const User = () => {
const { id } = useParams();
return (
<div>
<h1>User</h1>
<p>{`User ID: ${id}`}</p>
</div>
);
};
export default User;
详细的 react-router-dom
文档可以在 官方网站 中找到。