https://reacttraining.com/react-router/web/example/basic // git 實例地址
1.安裝 npm install react-router-dom --save
2.引入 import { BrowserRouter as Router, Route, Link } from "react-router-dom"
3.在組件根節點外面包裹一層<Router></Router>標簽
4.根據路徑跳轉 <Route path="/new" component={New} /> // path是路徑 ,component對應着組件 (此時輸入對應路徑即可跳轉到對應頁面)
5.<Link to="/new">New</Link> // 用Link標簽模擬一個人a標簽,點擊跳轉
import React from 'react' import LifeCycle from './lifeCycle' import New from './new' import Home from './Home' import { BrowserRouter as Router, Route, Link } from "react-router-dom" class RoutePage extends React.Component{ constructor(props) { super(props) this.state = { value: '路由跳轉頁面' } } render() { return( <Router> <div> <h3>{this.state.value}</h3> <Link to="/">Home</Link> <Link to="/about">New</Link> <Link to="/topics">LifeCycle</Link> <Route exact path="/" component={Home} /> // exact表示嚴格匹配 <Route path="/about" component={New} /> <Route path="/topics" component={LifeCycle} /> </div> </Router> ) } } export default RoutePage
動態路由
import React from 'react' import { BrowserRouter as Router, Route, Link } from "react-router-dom" import Content from './content' import GetTvalue from './getTvalue' class RouterPage extends React.Component{ constructor(props) { super(props) this.state = { value :'新聞頁面', arr: [ { aid: 1, title: 111 }, { aid: 2, title: 222 }, { aid: 3, title: 333 }, { aid: 4, title: 444 } ] } } render() { return( <Router> <div> <h3>動態路由</h3> { this.state.arr.map((value,key)=>{ return ( <li key={key}> <Link to={`/content/${value.aid}`}>{value.title}</Link> //對應着動態路由傳參 </li> ) }) } <Route path="/content/:aid" component={Content}></Route> //動態路由傳值path要照着這個格式寫,將參數名/:name以這種格式填寫 (跳轉的路由界面內容顯示處) <hr/> <br/> <h3>get方式傳值</h3> { this.state.arr.map((value,key)=>{ return ( <li key={key}> <Link to={`/gettvalue?aid=${value.aid}`}>{value.title}</Link> // 類似a標簽帶參數跳轉即可 </li> ) }) } <Route path="/gettvalue" component={GetTvalue}></Route> </div> </Router> ) } } export default RouterPage
在對應跳轉頁面參數值
//生命周期函數 componentDidMount() { console.log(this.props.location.search) // get方式時取值,取出來的時?aid=1這種格式,需手動轉或者引入url模塊,進行路由解析 console.log(this.props.match.params.aid); // 動態路由方式時取值 }