作者:专业STB | 来源:互联网 | 2023-10-10 06:50
react-router-dom的官方示例中,模糊匹配是比较简单的一个示例。
效果图如下:
在App.js中:
import React, {Component} from 'react';
import {BrowserRouter as Router,Route,Link,Switch,Redirect
} from &#39;react-router-dom&#39;;const routes &#61; [{ path: &#39;/&#39;,exact: true,sidebar: () &#61;> <div>home!div>,main: () &#61;> <h2>Homeh2>},{ path: &#39;/bubblegum&#39;,sidebar: () &#61;> <div>bubblegum!div>,main: () &#61;> <h2>Bubblegumh2>},{ path: &#39;/shoelaces&#39;,sidebar: () &#61;> <div>shoelaces!div>,main: () &#61;> <h2>Shoelacesh2>}
]const About &#61; () &#61;> <h2>Abouth2>
const Company &#61; () &#61;> <h2>Companyh2>
const User &#61; ({ match }) &#61;> (<div><h2>User: {match.params.user}h2>div>
)class App extends Component {constructor(props) {super(props);}render() {return (<Router><div><div style&#61;{{width: &#39;200px&#39;}}><ul><li><Link to&#61;"/about">About Us (static)Link>li><li><Link to&#61;"/company">Company (static)Link>li><li><Link to&#61;"/kim">Kim (dynamic)Link>li><li><Link to&#61;"/chris">Chris (dynamic)Link>li>ul>div><div style&#61;{{flex: 1}}><Switch><Route path&#61;"/about" component&#61;{About}/><Route path&#61;"/company" component&#61;{Company}/><Route path&#61;"/:user" component&#61;{User}/>Switch>div>div>Router>);}
}export default App;
在这个官方示例中&#xff0c;Link的to属性&#xff0c;对应一个页面。
在Route的path属性中&#xff0c;可以做到模糊匹配&#xff0c;并且你可以在模糊匹配的组件中&#xff0c;获取相关的参数。