react 路由的简单应用

react-router-dom 与 React-router是 5.x 版

1.安装 react-router-dom

npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令

 

2.先编写对应页面,如App、page,然后再新建一个路由组件,命名为“router.js”,并编写如下代码:

import React from 'react';
import {HashRouter, Route, Switch} from 'react-router-dom';
import App from './App'; 
import page from './page/page'


const BasicRoute  = () => (
    <HashRouter>
        <Switch>
            <Route exact path="/" component={App}/>
            <Route exact path="/next" component={page}/>
        </Switch>
    </HashRouter>
);


export default BasicRoute;

 

3.在根目录的“index.js”中引入路由组件 BasicRoute

import React from 'react';
import ReactDOM from 'react-dom';
import  BasicRoute  from './router';
import './index.css';

import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
     <BasicRoute/>,
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

4.此时运行项目,首页是App.js,使用<a href='#/next'>实现跳转,可以跳转到page.js。

<a href='#/next'><Button type="primary">go to next</Button></a>

 

posted @ 2021-09-27 17:44  不如饲猪  阅读(97)  评论(0编辑  收藏  举报