Reactルーター:オプションのパラメーター
提供:Dev Guides
React Routerを使用すると、パラメーターを簡単に使用できますが、これらはデフォルトで必須です。 ほとんどの場合、これで十分ですが、オプションのパラメーターが役立つ場合もあります。
オプションのパラメータを使用してルートを作成する
通常のパラメーターと同様に、オプションのパラメーターの宣言は、Route
のpath
プロパティの問題です。 疑問符で終わるパラメータはすべてオプションとして扱われます。
class App extends Component { render() { return ( <BrowserRouter> <div> {/* Optional parameters are defined by placing a question mark at the end of a parameter. */} {/* In this case, `line` is an optional parameter. */} {/* Optional parameters will be passed to the component, but will be undefined if not present in the URL. */} <Route path="/Lyrics/:song/:line?" component={LyricSheet}/> </div> </BrowserRouter> ); } }
ルートは、オプションのパラメータの有無にかかわらず、パスと一致する場合にレンダリングされます。 したがって、'/ Lyrics /Spoonman'と'/Lyrics / Spoonman /3'の両方が受け入れられます。
オプションパラメータの使用
オプションのパラメーターは、必須のパラメーターと一緒に小道具として渡されます。 ただし、URLに含まれていない場合は、未定義になります。
export default function LyricSheet({ match }) { const {line, song} = match.params; // Since `line` is an optional parameter, it'll either be undefined or a string. const lineNumber = line ? parseInt(line, 10) : -1; // Get the lyrics to the song. const lyrics = getLyrics(song) // Map the lyrics to components. If `index` is `lineNumber`, set `highlight` to `true`. .map((lyric, index) => (<LyricLine highlight={index === lineNumber} key={index} lyric={lyric} />)); return ( <div>{lyrics}</div> ); }
コンポーネントは、song
の歌詞を表示するようにレンダリングされます。 オプションのパラメータline
が定義されている場合、その行が強調表示されます。 GitHubのファイルをめくった場合、おそらくこのようなものを見たことがあるでしょう。
Reactの詳細については、 React.js シリーズのコーディング方法をご覧になるか、Reactトピックページで演習やプログラミングプロジェクトを確認してください。