react 使用和封裝路由(router.js)


使用route 之前需要先安裝 react-router-dom

yarn add react-router-dom -D

在src根目錄下新建router.js文件

//router.js
import React,{ Component } from 'react' import {Route, BrowserRouter, Switch, HashRouter} from 'react-router-dom' import Earnings from './page/earnings/earnings' import Home from './page/home/home' import UserVip from './page/userVip/userVip' export default class Router extends Component { render(){ return ( // 建議使用 HashRouter <HashRouter> <Switch>
            // exact 精准匹配 <Route path="/" exact component={ UserVip }></Route> <Route path="/earnings" component={ Earnings } /> <Route path="/home" component={ Home } />
            <Route component={ 如果前面的路由都沒有匹配上,在此處返回404頁面 } /> </Switch> </HashRouter> ) } }

 第二種寫法  

import {Route, BrowserRouter, Switch, HashRouter} from 'react-router-dom'
import Earnings from './page/earnings/earnings'
import Home from './page/home/home'
import UserVip from './page/userVip/userVip'

export default function Router() {
    return (
        <HashRouter>
            <Switch>
                <Route path="/" exact component={ UserVip }></Route>
                <Route path="/earnings" component={ Earnings } />
                <Route path="/home" component={ Home } />
                <Route component={ 如果前面的路由都沒有匹配上,在此處返回404頁面 } />
            </Switch>
        </HashRouter>
    )
}

使用 在index.js中引入router.js

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router'

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM