- 新建一个 router/index.js 文件
import React from 'react'
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'
import Home from './../views/home/home'
import About from './../views/about/about'
function router() {
return (
<Router>
<Route path="/home" component={Home} />
<Route path="/" render={
() => <Redirect to="/home" />}>
</Route>
<Route path="/about" component={About}></Route>
</Router>
)
}
export default router
- home组件
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
export default class Home extends Component {
render() {
return (
<div>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<h1>home</h1>
</div>
)
}
}
- about组件
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
export default class About extends Component {
render() {
return (
<div>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<h1>about</h1>
</div>
)
}
}
- app.js中引入router
import React, { Component } from 'react';
import Router from './router'
export default class App extends Component {
render(){
return (
<div>
<Router />
</div>
)
}
}
- 嵌套路由
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
export default class About extends Component {
render() {
return (
<div>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<h1>about</h1>
{this.props.children}
</div>
)
}
}
import React from 'react'
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'
import Home from './../views/home/home'
import About from './../views/about/about'
import somePage from './../views/somePage/somePage'
function router() {
return (
<Router>
<Route path="/home" component={Home} />
<Route path="/" render={
() => <Redirect to="/home" />}>
</Route>
<Route path="/about" render={()=>(
<About>
<Route path="/about/somePage" component={somePage} />
</About>
)}>
</Route>
</Router>
)
}
export default router