reactjs - 将组件作为道具传递给 Route 和在渲染函数中包装组件之间的区别
问题描述
路由到这样的组件有什么区别:
<Route path="coolPath" component={MyComponent} />
or
<Route path="coolPath" render={props => <MyComponent {...props} customProp="s" } />
对此:
<Route path"=coolPath">
<MyComponent />
</Route>
or
<Route path"=coolPath">
<MyComponent cusomProps="cp"/>
</Route>
解决方案
首先你应该通读这个网站:
https ://reacttraining.com/react-router/web/api/Route
但是要解释一下,这里发生了三件事,前两个是使用先前版本react-router
(v5 之前)的路由示例,第三个是react-router
(v5 - 当前)推荐的方法。
1. 带组件的路由
<Route path="/coolPath" component={MyComponent} />
这种类型的路由渲染传递给道具的单个组件。如果将内联函数传递给 Route 的component
prop,它将通过使用React.createElement
. 这可能效率低下,并且只能通过内联函数通过此方法传递自定义道具。React Router 的作者建议使用render
prop 而不是component
prop 来处理内联函数,如下所示。
2. 带渲染的路由
<Route path="/coolPath" render={props => <MyComponent {...props} customProp="s" } />
这种路由类型不是使用带有内联函数的组件属性为您创建一个新的 React 元素,而是传入一个函数,当位置匹配时调用,并且不会卸载组件并在重新渲染期间重新安装一个全新的组件。通过这种方法传递自定义道具也容易得多。
3.以children为组件的路由
<Route path="/coolPath">
<MyComponent customProp="s" />
</Route>
这是目前推荐的路由方式,当路由匹配到路径时,子组件会被渲染。使用这种方法传递自定义道具也很容易。
请记住,还有第四种类型,即:
4.以孩子为功能的路线
来自 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 道具。它的工作原理与 render 完全一样,只是无论是否匹配都会被调用。
推荐阅读
- python - 如何在keras的3D语义分割中在一卷的不同切片上放置不同的权重?
- java - groovy grails 无法将动态字符串传递给注释
- laravel - 如何在 Maatwebsite 中获取 excel 标题和标题?
- javascript - 每次更改的 React-Mutating 表单对象。无论如何我们可以用更好的方式做到这一点吗
- neo4j - Neo4j.Driver.V1.ServiceUnavailableException: '重试 5 次失败
- wordpress - 通过标签管理器设置归因,不确定语法是否正确
- c# - 如何添加列中的所有值并在表格页脚中显示添加的值
- javascript - React - 无法从道具设置组件的状态
- android - 如何在布局上放置圆形图像视图?
- sql - sql连接选择所有不可用的连接表的值