Reactルーターの概要
React Router は、何年にもわたっていくつかの変更を経てきました。 最新バージョンの紹介は次のとおりです。ReactRouter4。
Reactルーターのインストール
パッケージをインストールするのと同じです。 ただし、react-router
ではなくreact-router-dom
が必要になる可能性があります。
$ 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>
)を使用するべきではないのか疑問に思っている場合:ReactRouterは履歴オブジェクトに対していくつかの優れた機能を実行します。