React Router 使 使用参数很容易,但这些参数是默认的强制性。
创建具有可选参数的路线
与常规参数一样,声明可选参数只是路径
属性的问题;任何以问号结束的参数将被视为可选:
1class App extends Component {
2 render() {
3 return (
4 <BrowserRouter>
5 <div>
6 {/* Optional parameters are defined by placing a question mark at the end of a parameter. */}
7 {/* In this case, `line` is an optional parameter. */}
8 {/* Optional parameters will be passed to the component, but will be undefined if not present in the URL. */}
9 <Route path="/Lyrics/:song/:line?" component={LyricSheet}/>
10 </div>
11 </BrowserRouter>
12 );
13 }
14}
如果路径与路径相匹配,则路径将与可选参数相匹配,因此/Lyrics/Spoonman
和/Lyrics/Spoonman/3
都将被接受。
使用可选参数
可选参数被传递到强制性参数中,但如果它们不在URL中,它们将是未定义的:
1export default function LyricSheet({ match }) {
2 const {line, song} = match.params;
3 // Since `line` is an optional parameter, it'll either be undefined or a string.
4 const lineNumber = line ? parseInt(line, 10) : -1;
5 // Get the lyrics to the song.
6 const lyrics = getLyrics(song)
7 // Map the lyrics to components. If `index` is `lineNumber`, set `highlight` to `true`.
8 .map((lyric, index) => (<LyricLine highlight={index === lineNumber} key={index} lyric={lyric} />));
9 return (
10 <div>{lyrics}</div>
11 );
12}
该组件将被渲染以显示歌曲
的文字。如果定义了可选参数行
,该行将被突出。
如果您想了解更多关于 React 的信息,请查看我们的 如何在 React.js 中编码系列,或查看 我们的 React 主题页面以获取练习和编程项目。