首先你应该阅读这个网站:
https://v5.reactrouter.com/web/api/Route
但要解释一下,这里发生了三件事,前两个是使用以前版本的路由的示例react-router
(v5之前)第三个是react-router
(v5 - 当前)推荐方法。
1. 带组件的路由
<Route path="/coolPath" component={MyComponent} />
这种类型的路由渲染传递给 prop 的单个组件。如果将内联函数传递给 Route 的component
prop,它将通过使用在每个渲染上卸载并重新安装组件React.createElement
。这可能效率低下,并且只能通过内联函数通过此方法传递自定义道具。 React Router 的作者推荐使用render
道具而不是component
用于处理内联函数的 prop,如下所示。
2. 路由与渲染
<Route path="/coolPath" render={props => <MyComponent {...props} customProp="s" } />
此路由类型不是使用带有内联函数的 component 属性为您创建新的 React 元素,而是传递一个在位置匹配时调用的函数,并且不会在重新渲染期间卸载组件并重新安装全新的组件。通过此方法传递自定义道具也更容易。
3.以children为组件的路由
<Route path="/coolPath">
<MyComponent customProp="s" />
</Route>
这是目前推荐的路由方法,当路径与路由器匹配时,子组件将被渲染。使用此方法传递自定义道具也非常容易。
Keep in mind there is a fourth type, which is:
4.以children为函数的路由
来自reacttraining.com:
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
);
有时您需要渲染路径是否与位置匹配。在这些情况下,您可以使用 Children 属性函数。它的工作方式与渲染完全相同,只是无论是否匹配都会调用它。