React Router は、何年にもわたっていくつかの変更を経てきました。 最新バージョンの紹介は次のとおりです。ReactRouter4。
Reactルーターのインストール
パッケージをインストールするのと同じです。 あなたはおそらく欲しいでしょう react-router-dom
ではなく react-router
、 けれど:
$ yarn add react-router-dom
# or with npm:
$ npm install react-router-dom --save
ルートの設定
それは実際にはかなり直感的です。 ルーターの子要素でルートを定義するだけです。
import React, { Component } from 'react';
// This example's for browser use, so I'm using `BrowserRouter`.
// The are other routers for other environments, though.
import { BrowserRouter, Route } from 'react-router-dom';
// Your components.
import AboutPage from './AboutPage';
import HomePage from './HomePage';
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
{/* `component` will render when `path` matches the user's location */}
{/* `exact` makes it so it only renders if `path` matches exactly. */}
{/* Otherwise, `HomePage` would render on "mysite.com/About" as well as "mysite.com/". */}
<Route exact path="/" component={HomePage}/>
<Route path="/About" component={AboutPage}/>
</div>
</BrowserRouter>
);
}
}
export default App;
ルートへのリンク
もちろん、ユーザーが手動でURLを編集する必要がある場合、ルートはそれほど役に立ちません。 React Routerは、次の形式でソリューションを提供します。 Link
成分:
import React from 'react';
import { Link } from 'react-router-dom';
// Our Home Page. Exciting stuff.
export default function HomePage() {
return (
<div>
<h1>{'Home Page'}</h1>
{/* A link to the About route. */}
<Link to="/About">{'Check out our About Page!'}</Link>
</div>
);
}
なぜアンカータグを使用するべきではないのか疑問に思っている場合(<a>
):React Routerは、履歴オブジェクトを使っていくつかのすばらしい機能を実行します。