React Router允许从URL读取信息作为参数。
创建一个参数化的路径
它只是一个路径
的路径
属性的问题;任何从结肠开始的部分都将被视为参数:
1class App extends Component {
2 render() {
3 return (
4 <BrowserRouter>
5 <div>
6 <Route exact path="/" component={HomePage}/>
7 {/* Parameters are defined by placing a colon before a word. */}
8 {/* In this case, `username` is a parameter. */}
9 {/* Parameters will be passed to the component. */}
10 <Route path="/Users/:username" component={UserPage}/>
11 </div>
12 </BrowserRouter>
13 );
14 }
15}
当URL匹配路径(例如:‘/Users/Kevin’)时,该路径将被渲染。
使用参数
当然,除非你可以访问参数,否则这并不重要,因此,React Router将它们传输为属性:
1// Data from `Route` will be passed as a prop called `match`.
2function UserPage({ match }) {
3 return (
4 <div>
5 {/* The URL is passed as `match.url`. */}
6 {/* `match.url` and `match.path` will be defined whether or not the path is parameterized. */}
7 <div>{`The URL is "${match.url}"!`}</div>
8 {/* The path (the one you gave `Route`) is passed as `match.path`. */}
9 <div>{`It matched the path "${match.path}"!`}</div>
10 {/* The parameters are passed as `match.params`. */}
11 <div>{`The parameter is "${match.params.username}"!`}</div>
12 </div>
13 );
14}
match.params
将填充来自 URL 的值(即/Users/Kevin
,用户名
将是Kevin
).
参数可以位于路径的任何部分,而不仅仅是在路径的末端;例如,如果您想添加有关用户的朋友的页面,您可以在/Users/:username/Friends
中创建路线。