利用 react-router 创建一个单页应用

JavaScript,前端 2018-01-18

使用 create-react-app 创建一个新的项目

# 创建新项目 spa
create-react-app spa
# 进入该文件夹,并安装 react-router-dom 包
cd spa
npm i -S react-router-dom

note: 可能 npm 安装不了 react-router-dom 我下午尝试了多次,最后改用 yarn 才安装上。。然后没安装 create-react-app 的话,要先安装该包。

去掉我们不要的文件,最初的工作

清空 publicsrc 这两个文件夹的文件。然后新建一个 index.htmlpublic 文件夹里头。

<!-- ./public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
  <title>SPA</title>
</head>
<body>
  <div id="root">
    
  </div>
</body>
</html>

新建一个 index.js 文件,在 src 文件夹里头。

// ./src/index.js
import React from 'react';
import ReactDOM from 'react-dom';

import Main from './Main'

ReactDOM.render(
    <Main />, 
    document.getElementById('root')
);

主要的组件 Main.js

// ./src/Main.js

import React, { Component } from 'react'
import { Route, NavLink, HashRouter } from 'react-router-dom'

import Home from './Home'
import Test from './Test'
import './index.css'

class Main extends Component {
/**
 * HashRouter: 哈希路由
 * basename: {Str} 根路径
 * hashType: {Str} 不同的 hash 类型
 * 
 * 
 * NavLink: {Link} 的一个特殊版本 that will add styling attributes to the rendered element when it matches the current URL.
 *          The default given class is active.
 * exact: {Bool} true 代表精准匹配,如匹配规则为 '/' 那么 '/' 匹配成功,'/aa' 匹配失败。若为 false 则两者都成功匹配到
 * to: {Str} A string representation of the location to link to.
 *     {Obj} pathname, search, hash, state
 * activeClassName: {Str} The class to give the element when it is active.
 * activeStyle: {Obj} The styles to apply to the element when it is active.
 * Route: 路由
 * 三种 render() 方法:
 * component {Compontent}
 * render {Fn}
 * children {Fn}
 * 
 * 
 * path {Str} Any valid URL path that path-to-regexp understands.
 * exact {Bool} When true, will only match if the path matches the location.pathname exactly.
 * 
 */
    render() {
        return (
        <HashRouter>
            <div>
                <h1>hello react-router</h1>
                <ul className='header'>
                        <li><NavLink exact to="/">Home</NavLink></li>
                        <li><NavLink to="/test">test</NavLink></li>
                </ul>
                <div className='content'>
                    <Route exact path="/" component={Home} />
                    <Route path="/test" component={Test} />
                </div>
            </div>
        </HashRouter>
        )
    }
}

export default Main

两个标签页 Home 和 Test

// ./src/Home.js

import React, { Component } from 'react'

class Home extends Component {

    render() {
        return (
            <div>
                <h2>HELLO</h2>
                <p>Cras facilisis urna ornare ex volutpat, et
                convallis erat elementum. Ut aliquam, ipsum vitae
                gravida suscipit, metus dui bibendum est, eget rhoncus nibh
                metus nec massa. Maecenas hendrerit laoreet augue
                nec molestie. Cum sociis natoque penatibus et magnis
                dis parturient montes, nascetur ridiculus mus.</p>
                <p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
            </div>
        )
    }
}

export default Home
// ./src/Test.js

import React, { Component } from 'react'

class Test extends Component {
    render() {
        return (
            <div>
                <h2>Test</h2>
                <p>Mauris sem velit, vehicula eget sodales vitae,
        rhoncus eget sapien:</p>
                <ol>
                    <li>Nulla pulvinar diam</li>
                    <li>Facilisis bibendum</li>
                    <li>Vestibulum vulputate</li>
                    <li>Eget erat</li>
                    <li>Id porttitor</li>
                </ol>
            </div>
        );
    }
}

export default Test;

样式文件

/* ./src/index.css */

body {
    background-color: #FFCC00;
    padding: 20px;
    margin: 0;
}

h1,
h2,
p,
ul,
li {
    font-family: sans-serif;
}

ul.header li {
    display: inline;
    list-style-type: none;
    margin: 0;
}

ul.header {
    background-color: #111;
    padding: 0;
}

ul.header li a {
    color: #FFF;
    font-weight: bold;
    text-decoration: none;
    padding: 20px;
    display: inline-block;
}

.content {
    background-color: #FFF;
    padding: 20px;
}

.content h2 {
    padding: 0;
    margin: 0;
}

.content li {
    margin-bottom: 10px;
}
/* nav 选中时的样式 */
.active {
    background-color: #0099FF;
}

参考资料


本文由 阿涛 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论