React router的Route中component和render属性理解

本文介绍了React Router中Route组件的component、render和children这三个属性的用法和区别。重点强调了children属性的特殊性,即使路径不匹配也会渲染,并且在匹配与否的情况下都能接收路由属性。同时,警告不应在同一Route中同时使用component和render属性,因为children具有更高的优先级。建议在需要根据路由状态调整UI时使用children属性。
摘要由CSDN通过智能技术生成

最近在学习react-router现在写一下我对其中Route标签的三个互斥属性rendercomponentchildren的理解。

The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when its path matches the current URL.

Route 就是用来匹配路由的,并且对匹配到的路由就显示,所以会有可能两个以上的路由会匹配到,所以需要Switch标签包围,Switch可以帮助只渲染匹配到的第一个路由。

Route render methods
The recommended method of rendering something with a<Route>is to use children elements. There are, however, a few other methods you can use to render something with a <Route>. These are provided mostly for supporting apps that were built with earlier versions of the router before hooks were introduced.
<Route component>
<Route render>
<Route children> function
You should use only one of these props on a given . See their explanations below to understand the differences between them.
Route props
All three render methods will be passed the same three route props
match
location
history

一般情况下,Route推荐使用children元素方式配置路由,但是除此之外还有另外三种配置方法。
1.compnent (属性或者方法):
2.render(方法)
3.children(方法):children是只要配置了该属性,其里面返回的函数都会渲染,无论路径是否匹配。它能接受所有的路由属性,若不匹配match会为null
解释:

Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.The children render prop receives all the same route props as the component and render methods, except when a route fails to match the URL, then match is null. This allows you to dynamically adjust your UI based on whether or not the route matches. Here we’re adding an active class if the route matches

//Here we’re adding an active class if the route matches
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
);

//或者用于动画
<Route
  children={
   ({
    match, ...rest }) => (
    {
   /* Ani
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值