React路由最全使用(N)
React路由库的选择:
react-router
: 最初的React路由库,不依赖于React Router DOM。react-router-dom
: 提供Web界面的路由,依赖于react-router
。react-router-native
: 提供移动应用界面的路由,依赖于react-router
。react-router-config
: 用于静态路由的配置,需要配合react-router
使用。
安装依赖:
npm install react-router-dom
使用示例:
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;
const Users = () => <h2>Users</h2>;
const App = () => (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about/">About</Link>
</li>
<li>
<Link to="/users/">Users</Link>
</li>
</ul>
</nav>
{/* A <Route> is only ever rendered if it's path matches the current URL. */}
<Route path="/" exact component={Home} />
<Route path="/about/" component={About} />
<Route path="/users/" component={Users} />
</div>
</Router>
);
export default App;
在这个例子中,我们定义了三个组件Home
、About
和Users
,并通过Link
组件定义了导航链接。Router
组件提供路由功能,Route
组件根据当前URL路径渲染对应的组件。
评论已关闭