Reactルーターパラメーター
React Router を使用すると、URLからパラメーターとして情報を読み取ることができます。
パラメータ化されたルートの作成
それはただの問題です path
のプロパティ Route
; コロンで始まるセグメントはすべてパラメータとして扱われます。
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/" component={HomePage}/>
{/* Parameters are defined by placing a colon before a word. */}
{/* In this case, `username` is a parameter. */}
{/* Parameters will be passed to the component. */}
<Route path="/Users/:username" component={UserPage}/>
</div>
</BrowserRouter>
);
}
}
URLがパス(例:‘/ Users / Kevin’ )と一致すると、そのルートがレンダリングされます。
パラメータの使用
もちろん、パラメータにアクセスできない限り、それはあまり意味がありません。 したがって、ReactRouterはそれらをプロパティとして渡します。
// Data from `Route` will be passed as a prop called `match`.
function UserPage({ match }) {
return (
<div>
{/* The URL is passed as `match.url`. */}
{/* `match.url` and `match.path` will be defined whether or not the path is parameterized. */}
<div>{`The URL is "${match.url}"!`}</div>
{/* The path (the one you gave `Route`) is passed as `match.path`. */}
<div>{`It matched the path "${match.path}"!`}</div>
{/* The parameters are passed as `match.params`. */}
<div>{`The parameter is "${match.params.username}"!`}</div>
</div>
);
}
match.params
URLの値が入力されます(つまり、 ‘/ Users / Kevin’ の場合、 username
‘Kevin’ )になります。
パラメータは、パスの最後だけでなく、パスの任意の部分に含めることができます。 たとえば、ユーザーの友達に関するページを追加したい場合は、次の場所にルートを作成できます。 /Users/:username/Friends
.