react路由的一个简单例子

Posted on 2020-11-15 02:43  猫头唔食鱼  阅读(240)  评论(0编辑  收藏  举报

1.安装

yarn add react-router-dom

2.引入 BrowserRouter, Route, Link 

import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'

3.创建无状态组件

function Index() {
    return <div>
        首页
    </div>
}

function List() {
    return <div>列表</div>
}

function Test() {
    return (
        <div>
            {/* Router标签包裹Link标签和Route标签 */}
            <Router>
                <ul>
                    <li>
                        <Link to="/">首页</Link>
                    </li>
                    <li>
                        <Link to='/list/'>列表</Link>
                    </li>
                </ul>
                <Route path="/" exact component={Index}></Route>
                <Route path="/list/" component={List}></Route>
            </Router>
        </div>
    )
}
export default Test