在React 中 处处皆组件!! Router 这也是一个组件,有点不怎么好用
一: 安装 react-router-dom
1 | npm install react-router-dom |
二: 简单使用方法
在 src/app.js 中 用以下代码
1 | import React from "react"; |
三: Router 详解
3.1 Router 的引入
每个React Router应用程序的核心应该是路由器组件。对于Web项目,react-router-dom提供
因此需要在 把根组件包囊在 router 组件内部
1 | import React from "react"; |
3.2 Router 的匹配
使用 Switch, Route 这两个组件 来匹配路由。
React Router提供了一个组件来在您的应用程序中创建链接。无论在何处呈现,锚点()都将呈现在HTML文档中。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
function App() {
return (
<div>
<Switch>
{/* If the current URL is /about, this route is rendered
while the rest are ignored */}
<Route path="/about">
<About />
</Route>
{/* Note how these two routes are ordered. The more specific
path="/contact/:id" comes before path="/contact" so that
route will render when viewing an individual contact */}
<Route path="/contact/:id">
<Contact />
</Route>
<Route path="/contact">
<AllContacts />
</Route>
{/* If none of the previous routes render anything,
this route acts as a fallback.
Important: A route with path="/" will *always* match
the URL because all URLs begin with a /. So that's
why we put this one last of all */}
<Route path="/">
<Home />
</Route>
</Switch>
</div>
);
}
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);3.3 路由跳转
1
2
3
4
5
6
7
8
9
10
11
12
13
14<Link to="/">Home</Link>
// <a href="/">Home</a>
//The <NavLink> is a special type of <Link> that can style itself as “active” when its to prop matches the current location.
<NavLink to="/react" activeClassName="hurray">
React
</NavLink>
// When the URL is /react, this renders:
// <a href="/react" className="hurray">React</a>
// When it's something else:
// <a href="/react">React</a>