再過去版本中可使用IndexRoute作為設定首頁進入點,但在React Router 4設定上有所改變,全都使用Route,而需要設定為首頁加入exact屬性。在Layout方面本來使用Route帶入元件,在React Router 4直接使用react元件,如下在Layout元件中使用this.props.children顯示子路由。

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Router, Route, Switch } from "react-router";
import { BrowserRouter, HashRouter, Link } from "react-router-dom";
class Layout extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
                <h1>App</h1>
                <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/about">About</Link>
                    </li>
                    <li>
                        <Link to="/about2">About2</Link>
                    </li>
                </ul>
                {this.props.children}
            </div>
        );
    }
}
class About extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <div>about</div>;
    }
}class About2 extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <div>about2</div>;
    }
}
class Home extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>home
                <div>
                    <Link to="/about"> 
                        Link About
                    </Link>
                </div>
            </div>
        );
    }
}
class App extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <HashRouter>
                <Switch>
                    <Route
                        exact
                        path="/"
                        component={Home}
                    />
                    <Layout>
                        <Route path="/about" component={About} />
                        <Route path="/about2" component={About2} />
                    </Layout>
                </Switch>
            </HashRouter>
        );
    }
}
ReactDOM.render(<App />, document.getElementById("root"));

您也可能喜歡這些文章