安裝路由:html
npm i react-router-dom前端
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class About extends Component { render() { console.log(this.props) return ( <div> About <Link to={{ pathname:'/about/a' , search:'?num=0' }}><button>A</button></Link> <Link to={{ pathname:'/about/b', search:'?num=1' }} ><button>B</button></Link> <Link to="/about/d"><button>D模板</button></Link> </div> ); } } export default About;
import React, { Component } from 'react'; import { Route,Link,Switch } from 'react-router-dom'; import Home from './component/home'; import About from './component/about'; import Aboutc from './component/aboutc'; import Aboutd from './component/aboutd'; class App extends Component { render() { return ( <div> <Link to='/'><button>首頁</button></Link> <Link to='/about'><button>關於</button></Link> <Route exact path='/' component={Home}/> <Route path='/about' render={(props)=>{ return <About {...props}/> }}/> <Switch> <Route path='/about/d' component={Aboutd}/> <Route path='/about/:id' component={Aboutc}/> </Switch> </div> ); } } export default App;
(當組件拿不到 props 的時候,可使用 withRouter 去包一下)react
import React, { Component } from 'react'; import {withRouter} from 'react-router-dom'; class BackHome extends Component { back = () => { this.props.history.push('/'); } render() { return ( <div> <button onClick={this.back}>返回首頁</button> </div> ); } } export default withRouter(BackHome);
PropTypes: 可以驗證父級傳遞進來的數據類型(爲了報錯)npm