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

时间:2019-12-09 20:28:27

标签: reactjs routes react-router react-router-v4 react-router-v5

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

 <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>

1 个答案:

答案 0 :(得分:2)

首先,您应该阅读以下网站:
https://reacttraining.com/react-router/web/api/Route

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

1。使用组件进行路由

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

这种类型的路线呈现传递给道具的单个组件。如果将内联函数传递给Route的component道具,它将通过使用React.createElement在每个渲染器上卸载并重新安装组件。这可能效率很低,并且只能通过内联函数通过此方法传递自定义道具。 React Router的作者建议使用render道具而不是component道具来处理内联函数,如下所示。

2。使用渲染路线

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

与其使用带有内联函数的component属性为您创建一个新的React元素,当位置匹配时该路由类型将传递一个要调用的函数,并且不会在重新渲染期间卸载组件并重新安装全新的组件。通过此方法传递自定义道具也容易得多。

3。以儿童为组成部分的路线

<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
);

有时您需要渲染路径是否与位置匹配。在这种情况下,您可以使用child道具功能。它与render完全一样,除了是否存在匹配项而被调用。