react-router-dom 使用

demo 使用 creat-react-app 脚手架
安装 yarn add react-router-dom -S
"dependencies": {
    "react-router-dom": "^5.1.2"
 }

简单路由使用

  1. src/components 目录下创建 Home.js, TodoList.js 用于路由界面显示

Home.js


import React from "react";

function Home() {
    return (
        
Home
) } export default Home;

TodoList.js


import React from "react";

function TodoList() {
    return (
        
TodoList
) } export default TodoList;
  1. src 目录下创建 BasicRoute.js 配置路由

BasicRoute.js

import React from 'react'
import Home from './components/Home'
import TodoList from './components/TodoList'
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'

function BasicRoute() {
    return (
        
Home
TodoList
); } export default BasicRoute;
  1. src 目录下改写 App.js
import React from 'react'
import BasicRoute from "./BasicRoute"
import './App.css'

function App() {
    return (
        
); } export default App;

路由嵌套使用

  1. 基于上面基础 src/components 目录下创建 Detail.js, DetailChildOne.js DetailChildTwo.js用于路由界面显示

Detail.js 注:略有不同


import React from 'react';
import {withRouter, Link} from 'react-router-dom';

// 要使用 React.Component
class Detail extends React.Component {
    render() {
        return (
            
Detail页面
嵌套路由DetailChildOne页面
嵌套路由DetailChildTwo页面 {/*嵌套的页面显示在这里*/} {this.props.children}
) } } // 将组件包裹进 Route, 然后返回 export default withRouter(Detail);

DetailChildOne.js


import React from "react";

function DetailChildOne() {
    return (
        
DetailChildOne
) } export default DetailChildOne;

DetailChildTwo.js


import React from "react";

function DetailChildTwo() {
    return (
        
DetailChildTwo
) } export default DetailChildTwo;

修改 BasicRoute.js

import React from 'react'
import Home from './components/Home'
import Detail from './components/Detail'
import DetailChildOne from './components/DetailChildOne'
import DetailChildTwo from './components/DetailChildTwo'
import TodoList from './components/TodoList'
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'

function BasicRoute() {
    return (
        
Home
Detail
TodoList
{/*嵌套路由*/} }/>
); } export default BasicRoute;

exact使用

  • exact是Route的一个属性,认为其是一种严格匹配模式

  • 当exact为false时,根据路由匹配所有组件,如"/" 匹配 “/”、“/Home”、“/Home/menu”;

  • 当exact为true时,则“/” 仅匹配“/”、无法匹配到“/Home”。

url传参

  1. 通配符传参

Route:


Link:

通配符

参数获取:

this.props.match.params.name
  1. query传参

Route:


Link:

var query = {
        pathname: '/query',
        query: '我是通过query传值 '
}

query

参数获取:

this.props.location.query

3.state传参

Route:

state

Link:

var state = {
        pathname: '/state',
        state: '我是通过state传值'
    }


参数获取:

this.props.location.state

你可能感兴趣的:(react-router-dom 使用)