使用 React 和 React 路由器的 Hello World

一旦你安装了 reactreact-router,就可以把它们放在一起了。

语法非常简单,你可以在打开该 URL 时指定要渲染的 urlcomponent

<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 页面。