//App.js
import {
BrowserRouter as Router,
Route,
Link,
} from "react-router-dom";
// 引入組件
import Home from "....";
import News from "...."
function App() {
return (
<Router>
<Link to="/">首頁</Link>
<Link to="/news">新聞</Link>
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
</Router>
);
}
export defautl App;
如何傳遞參數(3種)
1、params傳參(動態路由)
特點:刷新頁面參數不消失,參數會在地址欄顯示
- 路由配置
<Route path='/about/:id' component={About} />
- 跳轉方式
//傳遞參數可以拆分為對象寫法:{pathname:'/about/3'}
//html:
<Link to={'/about/3'}>點擊跳轉</Link>
//js:
this.props.history.push('/about/3')
- 獲取值
this.props.match.params.id // 3
2、query傳參
特點:刷新頁面參數消失,參數不會在地址欄顯示
- 路由配置
<Route path='/about' component={About} />
- 跳轉方式
//html:
<Link to={{pathname:'/about', query:{id:3}}}>點擊跳轉</Link>
//js:
this.props.history.push({pathname:'/about', query:{id:3}})
- 獲取值
this.props.location.query.id // 3
3、state傳參
特點:刷新頁面參數不消失,參數不會在地址欄顯示
- 路由配置
<Route path='/about' component={About} />
- 跳轉方式
//html:
<Link to={{pathname:'/about', state:{id:3}}}>點擊跳轉</Link>
//js:
this.props.history.push({pathname:'/about', state:{id:3}})
- 獲取值
this.props.location.state.id // 3