react路由操作
阿新 • • 發佈:2022-04-15
路由
- 需要安裝react路由外掛
npm i --save react-router-dom #功能更全
hash模式
import { HashRouter, Route, Link } from "react-router-dom"; render() { return ( <HashRouter> <div> <header className="title"> <Link to="/">首頁</Link> <Link to="/news">新聞</Link> <Link to="/product">商品</Link> </header> <br /> <hr /> <br /> <Route exact path="/" component={Home} /> <Route path="/news" component={News} /> <Route path="/product" component={Product} /> </div> </HashRouter> ); }
history模式
import { BrowserRouter as Router, Route, Link } from "react-router-dom" render() { return ( <Router> <div> <header className="title"> <Link to="/">首頁</Link> <Link to="/news">新聞</Link> <Link to="/product">商品</Link> </header> <br /> <hr /> <br /> <Route exact path="/" component={Home} /> <Route path="/news" component={News} /> <Route path="/product" component={Product} /> </div> </Router> ); }
路由跳轉和增加引數
import React, { Component } from 'react'; class News extends Component { constructor(props) { super(props); this.data = { value: null }; } componentWillMount(){ console.log('測試',this.data) } render(){ const btnNav = ()=> { this.props.history.push({ pathname:'/', search:'name' }); } return ( <div className="News"> 當前是News頁面 <button onClick={btnNav}>跳轉到Home頁面</button> </div> ); } } export default News; # 明傳 this.props.history.push({ pathname:'/', search: 'name=1' }); # 暗傳 this.props.history.push({ pathname:'/', state: { test: 'dashboard' } }); # 接收引數 ## Search this.props.history.location.search ## State this.props.history.location.state