React Router的Route的使用

Route 是 React Router中用于配置路由信息的组件,每当有一个组件需要根据 URL 决定是否渲染时,就需要创建一个 Route。

1) path

每个 Route 都需要定义一个 path 属性,path 属性是一个url,当 URL 匹配一个 Route 时,这个 Route 中定义的组件就会被渲染出来。

2)Route 渲染组件的方式

(1)component

component 的值是一个组件,当 URL 和 Route 匹配时,Component属性定义的组件就会被渲染。例如:

<Route path='/foo' component={Foo} >

当 URL = "http://example.com/foo" 时,Foo组件会被渲染。

(2) render

render 的值是一个函数,这个函数返回一个 React 元素。这种方式方便地为待渲染的组件传递额外的属性。例如:

1 <Route path='/foo' render={(props) => {
2  <Foo {...props} data={extraProps} />
3 }}>
4 </Route>

Foo 组件接收了一个额外的 data 属性。

(3)children

children 的值也是一个函数,函数返回要渲染的 React 元素。 与前两种方式不同之处是,无论是否匹配成功, children 返回的组件都会被渲染。但是,当匹配不成功时,match 属性为 null。例如:

1 <Route path='/foo' render={(props) => {
2  <div className={props.match ? 'active': ''}>
3   <Foo {...props} data={extraProps} />
4  </div>
5 }}>
6 </Route> 

如果 Route 匹配当前 URL,待渲染元素的根节点 div 的 class 将设置成 active.

单独介绍:react 路由render属性

作用: 能够更方便地给组件传递额外的属性

<Route path={xx} render={props=>{ return <组件 {...props}></组件> </Route>

因为渲染的组件不是路由组件,所以需要传入props

 1 import React from 'react';
 2 import './App.css';
 3 import {Switch,Route,Redirect} from 'react-router-dom'
 4 import {Button} from 'antd'
 5 import 'antd/dist/antd.css'
 6 import {adminRoutes} from './routes/index'
 7 
 8 function App() {
 9   return (
10     <div className="App">
11       <h1>app</h1>
12       <Switch>
13         {adminRoutes.map(route=>{
14           return <Route  key={route.path} path={route.path} exact={route.exact} render={routeProps=>{
15             return <route.component {...routeProps}></route.component> 
16           }}></Route>
17         })}
18         <Redirect to='/404'></Redirect>
19       </Switch>
20     </div>
21   );
22 }
23 
24 export default App;
原文地址:https://www.cnblogs.com/shun1015/p/14663317.html