React項目使用React-Router


⒈初始化React項目(略)

  請參考  初始化一個React項目(TypeScript環境)

⒉集成React-Router

  在React世界里,公認最好用的路由是React-Router。那我們直接來集成它吧。

yarn add react-router history
#如果是type環境
yarn add react-router @types/react-router history @types/history

⒊配置React-Router

  在src中新建一個文件叫Router.js(如果是type環境則名稱為Router.tsx):

cd src
cd.>Router.js #如果是type環境 cd.>Router.tsx

  代碼如下:

import {createBrowserHistory} from 'history';
import React from 'react';
import {Route,Router} from 'react-router';
import App from './App';
import Edit from './Edit';

const history = createBrowserHistory()

export default () => (
  <Router history={history}>
    <>
      <Route exact path="/" component={App}/>
    </>
  </Router>
)

  然后修改index.js(type環境為index.tsx)文件,將讀取的組件修改為Router:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// import App from './App';
import * as serviceWorker from './serviceWorker';
import Router from './Router';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

  刷新一下頁面,運行正常

  那我們再添加一個頁面Edit.js(type環境為Edit.tsx),並為它配好路由:

Edit.js
import React from 'react';

export default () => (
  <div>Edit</div>
)
Router.js
import {createBrowserHistory} from 'history';
import React from 'react';
import {Route,Router} from 'react-router';
import App from './App';
import Edit from './Edit';

const history = createBrowserHistory()

export default () => (
  <Router history={history}>
    <>
      <Route exact path="/" component={App}/>
      <Route path="/edit" component={Edit}/>
    </>
  </Router>
)


免責聲明!

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



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