React Router 4子路由使用Layout設定

2 月 23, 2019 | Javascript, | 0 comments

再過去版本中可使用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="/"></link>Home
                    </li>
                    <li>
                        <link to="/about"></link>About
                    </li>
                    <li>
                        <link to="/about2"></link>About2
                    </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> 
                        Link About

                </div>
            </div>
        );
    }
}
class App extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <hashrouter>
                <switch>
                    <route component="{Home}" exact="" path="/"></route>
                    <layout>
                        <route component="{About}" path="/about"></route>
                        <route component="{About2}" path="/about2"></route>
                    </layout>
                </switch>
            </hashrouter>
        );
    }
}
ReactDOM.render(<app></app>, document.getElementById(root));