首页 > 解决方案 > 将组件作为道具传递给 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>

标签: reactjsroutesreact-routerreact-router-v4react-router-v5

解决方案


首先你应该通读这个网站:
https ://reacttraining.com/react-router/web/api/Route

但是要解释一下,这里发生了三件事,前两个是使用先前版本react-router(v5 之前)的路由示例,第三个是react-router(v5 - 当前)推荐的方法。

1. 带组件的路由

<Route path="/coolPath" component={MyComponent} />

这种类型的路由渲染传递给道具的单个组件。如果将内联函数传递给 Route 的componentprop,它将通过使用React.createElement. 这可能效率低下,并且只能通过内联函数通过此方法传递自定义道具。React Router 的作者建议使用renderprop 而不是componentprop 来处理内联函数,如下所示。

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 完全一样,只是无论是否匹配都会被调用。


推荐阅读