React 路由器概述

React Router多年来经历了一些变化,这里是最新版本的介绍:React Router 4。

安装 React 路由器

您可能想要react-router-dom,而不是react-router,尽管:

1$ yarn add react-router-dom
2
3# or with npm:
4$ npm install react-router-dom --save

设置路线

它实际上非常直观,只需在路由器的儿童元素中定义路线:

 1import React, { Component } from 'react';
 2// This example's for browser use, so I'm using `BrowserRouter`.
 3// The are other routers for other environments, though.
 4import { BrowserRouter, Route } from 'react-router-dom';
 5
 6// Your components.
 7import AboutPage from './AboutPage';
 8import HomePage from './HomePage';
 9
10class App extends Component {
11  render() {
12    return (
13      <BrowserRouter>
14        <div>
15          {/* `component` will render when `path` matches the user's location */}
16          {/* `exact` makes it so it only renders if `path` matches exactly. */}
17          {/* Otherwise, `HomePage` would render on "mysite.com/About" as well as "mysite.com/". */}
18          <Route exact path="/" component={HomePage}/>
19          <Route path="/About" component={AboutPage}/>
20        </div>
21      </BrowserRouter>
22    );
23  }
24}
25
26export default App;

连接到路线

当然,如果用户必须手动编辑URL,路由器不会那么有用,React Router提供了一个解决方案,以链接组件的形式:

 1import React from 'react';
 2import { Link } from 'react-router-dom';
 3
 4// Our Home Page. Exciting stuff.
 5export default function HomePage() {
 6  return (
 7    <div>
 8      <h1>{'Home Page'}</h1>
 9      {/* A link to the About route. */}
10      <Link to="/About">{'Check out our About Page!'}</Link>
11    </div>
12  );
13}

如果你想知道为什么不应该只使用标签(<a>):React Router 会对历史对象做一些很酷的事情。

Published At
Categories with 技术
Tagged with
comments powered by Disqus