将组件作为 prop 传递给 Route 与在渲染函数中包装组件之间的区别

2023-11-27

路由到这样的组件有什么区别:

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

or

<Route
  path="coolPath"
  render={props => <MyComponent {...props} customProp="s" }
/>

To this:

<Route path"=coolPath">
  <MyComponent />
</Route>

or

<Route path"=coolPath">
  <MyComponent cusomProps="cp"/>
</Route>

首先你应该阅读这个网站:
https://v5.reactrouter.com/web/api/Route

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

1. 带组件的路由

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

这种类型的路由渲染传递给 prop 的单个组件。如果将内联函数传递给 Route 的componentprop,它将通过使用在每个渲染上卸载并重新安装组件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 属性函数。它的工作方式与渲染完全相同,只是无论是否匹配都会调用它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将组件作为 prop 传递给 Route 与在渲染函数中包装组件之间的区别 的相关文章

随机推荐