最近在学习react-router
现在写一下我对其中Route标签的三个互斥属性render
、component
、children
的理解。
The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when its path matches the current URL.
Route 就是用来匹配路由的,并且对匹配到的路由就显示,所以会有可能两个以上的路由会匹配到,所以需要Switch标签包围,Switch可以帮助只渲染匹配到的第一个路由。
Route render methods
The recommended method of rendering something with a<Route>
is to use children elements. There are, however, a few other methods you can use to render something with a<Route>
. These are provided mostly for supporting apps that were built with earlier versions of the router before hooks were introduced.
<Route component>
<Route render>
<Route children> function
You should use only one of these props on a given . See their explanations below to understand the differences between them.
Route props
All three render methods will be passed the same three route props
match
location
history
一般情况下,Route推荐使用children元素方式配置路由,但是除此之外还有另外三种配置方法。
1.compnent (属性或者方法):
2.render(方法)
3.children(方法):children是只要配置了该属性,其里面返回的函数都会渲染,无论路径是否匹配。它能接受所有的路由属性,若不匹配match
会为null
解释:
Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.The children render prop receives all the same route props as the component and render methods, except when a route fails to match the URL, then match is null. This allows you to dynamically adjust your UI based on whether or not the route matches. Here we’re adding an active class if the route matches
//Here we’re adding an active class if the route matches
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Link,
Route
} from "react-router-dom";
function ListItemLink({
to, ...rest }) {
return (
<Route
path={
to}
children={
({
match }) => (
<li className={
match ? "active" : ""}>
<Link to={
to} {
...rest} />
</li>
)}
/>
);
}
ReactDOM.render(
<Router>
<ul>
<ListItemLink to="/somewhere" />
<ListItemLink to="/somewhere-else" />
</ul>
</Router>,
node
);
//或者用于动画
<Route
children={
({
match, ...rest }) => (
{
/* Ani