使用 React 和 React 路由器的 Hello World
一旦你安裝了 react
和 react-router
,就可以把它們放在一起了。
語法非常簡單,你可以在開啟該 URL 時指定要渲染的 url
和 component
<Route path="hello" component={ HelloComponent } />
這意味著當 url 路徑為 hello
時,渲染元件 HelloComponent
FILENAME: app.js
'use strict';
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory, Link } from 'react-router';
// These are just demo components which render different text.
let DashboardPage = () => (
<div>
<h1>Welcome User</h1>
<p>This is your dashboard and I am an example of a stateless functional component.</p>
<Link to="/settings">Goto Settings Page</Link>
</div>
)
let SettingsPage = () => (
<div>
<h1>Manage your settings</h1>
<p>display the settings form fields here...or whatever you want</p>
<Link to="/">Back to Dashboard Page</Link>
</div>
)
let AuthLoginPage = () => (
<div>
<h1>Login Now</h1>
<div>
<form action="">
<input type="text" name="email" placeholder="email address" />
<input type="password" name="password" placeholder="password" />
<button type="submit">Login</button>
</form>
</div>
</div>
)
let AuthLogoutPage = () => (
<div>
<h1>You have been successfully logged out.</h1>
<div style={{ marginTop: 30 }}>
<Link to="/auth/login">Back to login page</Link>
</div>
</div>
)
let ArticlePage = ({ params }) => (
<h3>Article {params.id}</h3>
)
let PageNotFound = () => (
<div>
<h1>The page you're looking for doesn't exist.</h1>
</div>
)
// Here we pass Router to the render function.
render( (
<Router history={ browserHistory }>
<Route path="/" component={ DashboardPage } />
<Route path="settings" component={ SettingsPage } />
<Route path="auth">
<IndexRoute component={ AuthLoginPage } />
<Route path="login" component={ AuthLoginPage } />
<Route path="logout" component={ AuthLogoutPage } />
</Route>
<Route path="articles/:id" component={ ArticlePage } />
<Route path="*" component={ PageNotFound } />
</Router>
), document.body );
路由引數 :路由器路徑可以配置為獲取引數,以便我們可以讀取元件的引數值。<Route path="articles/:id" component={ ArticlePage } />
的路徑有一個/:id
。這個 id
變數用於路徑引數的目的,它可以通過 {props.params.id}
在元件 ArticlePage
上訪問。
如果我們訪問 http://localhost:3000/#/articles/123
然後 {props.params.id}
在元件 ArticlePage
將被解析為 123.但訪問 url http://localhost:3000/#/articles
,將無法工作,因為沒有 id 引數。
路線引數可以由可選的通過在一對括號之間寫它:
<Route path="articles(/:id)" component={ ArticlePage } />
如果你想使用子路線,那麼你可以這樣做
<Route path="path" component={ PathComponent }>
<Route path="subpath" component={ SubPathComponent } />
</Route>
- 當訪問
/path
時,將呈現PathComponent
- 當訪問
/path/subpath
時,將渲染PathComponent
並將SubPathComponent
作為props.children
傳遞給它
你可以使用 path="*"
來捕獲所有不存在的路由並呈現 404 page not found
頁面。