React路由配置使用
Router包安装:
安装包还是要打开命令行工具,使用npm来进行安装。
npm install --save react-router react-router-dom
页面login:
import React from 'react' import { createHashHistory } from 'history' // eslint-disable-next-line react/require-render-return export default class pagea extends React.Component{ jumpHome(){ createHashHistory().push('home') } jumpRegis(){ createHashHistory().push('register') } render(){ return( <div> <div><br/><br/><br/><br/>login</div> <button onClick={this.jumpHome}>login</button> <button onClick={this.jumpRegis}>register</button> </div> ) } }
页面a:
import React from 'react' export default class pagea extends React.Component{ render(){ return( <div> <div><br/><br/><br/><br/>页面A</div> </div> ) } }
页面B:
import React from 'react' export default class pageb extends React.Component{ render(){ return( <div> <div>页面B</div> </div> ) } }
home.js:
import React from 'react'; import {NavLink} from 'react-router-dom'; const NavBar = () =>( <div> <div> <NavLink exact to='/home/pagea'>pagea</NavLink><br/> <NavLink to='/home/pageb'>pageb</NavLink> </div> </div> ) export default NavBar;
index.js:
import React from 'react'; import ReactDOM from 'react-dom'; import * as serviceWorker from './serviceWorker'; import {BrowserRouter as Router ,HashRouter,MemoryRouter, Route , Switch ,Redirect} from 'react-router-dom'; import Login from './components/login' import Register from './components/register' import Home from './home'; import Pagea from './components/pagea' import Pageb from './components/pageb' ReactDOM.render( <HashRouter basename="" > <div> <Route exact path="/" component={Login} /> <Route path="/login" component={Login} /> <Route path="/register" component={Register} /> <Route path="/home" component={Home}> <Route path="/home" component={Home}/> <Route path="/home/pagea" component={Pagea} /> <Route path="/home/pageb" component={Pageb} /> </Route> </div> </HashRouter>, document.getElementById('root') ) serviceWorker.unregister();
项目结构: