路由的原理,依據 url 請求,動態去載入相對應的元件。
npm install react-router-dom --save // 基於 react-router 實作的 lib npm install @types/react-router-dom --save-deve // 官方沒提供
React 路由用法主要是由這三個所組成
BroserRouter + Switch+ Route
app.tsx <BroserRouter> <Switch> <Route exect path="/" component={HomePage} /> <Route path="/sign" render={()=><h1>sign</h1>} /> <Route render={()=><h1>404</h1>} /> </Switch> </BroserRouter>
http://localhost:3000/product?id=5
http://localhost:3000/product/123456
import React from "react"; import { RouteComponentProps } from "react-router-dom"; interface MatchParams { touristRouteId: string; } export const DetailPage: React.FC<RouteComponentProps<MatchParams>> = ( props ) => { // console.log(props.history); // console.log(props.location); // console.log(props.match); return <h1>路游路線詳情頁面, 路線ID: {props.match.params.touristRouteId}</h1>; };
使用組件 React Route 時,預設會在子組件中 props 取得 match 、history、location ,但如果要跨組件傳遞時則
import React,{Component} from 'react' import {withRouter} from 'react-router-dom' class App extends Component{ console.log(this.props); // {match: {…}, location: {…}, history: {…}, 等} render(){return (<div className='app'></div>) } } export default withRouter(App); // 這里透遛WithRouter將路由參數傳入props中
import { useHistory, useLocation, useParams, useRouteMatch } from "react-router-dom"; const history = useHistory(); const location = useLocation(); const { touristRouteId }: MatchParams = useParams(); const match = useRouteMatch();
React 導頁的方式主要有兩種
<Button onClick={() => history.push("signIn")}>登入</Button>
<Link to={`detail/${id}`}> 連結 </Link>