import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; function ParamsExample() { return ( <Router> <div> <h2>Accounts</h2> <ul> <li> <Link to="/netflix">Netflix</Link> </li> <li> <Link to="/zillow-group">Zillow Group</Link> </li> <li> <Link to="/yahoo">Yahoo</Link> </li> <li> <Link to="/modus-create">Modus Create</Link> </li> </ul> <Route path="/:id" component={Child} /> {/* It's possible to use regular expressions to control what param values should be matched. * "/order/asc" - matched * "/order/desc" - matched * "/order/foo" - not matched */} <Route path="/order/:direction(asc|desc)" component={ComponentWithRegex} /> {/*若是路徑匹配的是/order/asc或者/order/desc這個ComponentWithRegex組件就會顯示出來,不然不會顯示*/} </div> </Router> ); } function Child({ match }) { //Object {path: "/:id", url: "/netflix", isExact: true, params: Object}這裏的match裏面是路由信息參數 console.log(match); return ( <div> <h3>ID: {match.params.id}</h3> </div> ); } function ComponentWithRegex({ match }) { return ( <div> <h3>Only asc/desc are allowed: {match.params.direction}</h3> </div> ); } export default ParamsExample;
轉載自https://reacttraining.com/react-router/web/example/url-paramsreact