React Router(二):URL传参和嵌套路由

一、如何通过URL传递参数

URL传递参数是传给匹配到的组件,组件可以根据参数渲染不同的内容

很简单,所以直接上代码了,结合注释看

import React from "react";
import {
     
  BrowserRouter as Router,
  Route,
  Link
} from "react-router-dom";

//这是一个路由的组件
//对于React Router render的组件,会传一个match的props给这个组件
const Topic = ({
      match }) => (
    //在match.props里面可以访问到定义的参数(id)
  <h1>Topic {
     match.params.id}</h1>
);

export default class RouterParams extends React.PureComponent {
     
  render() {
     
    return (
      <Router>
        <div>
          <ul id="menu">
            <li>
              <Link to="/topic/1">Topic 1</Link>
            </li>
            <li>
              <Link to="/topic/2">Topic 2</Link>
            </li>
            <li>
              <Link to="/topic/3">Topic 3</Link>
            </li>
          </ul>
		  //路由的定义
          <div id="page-container">
            <Route path="/topic/:id" component={
     Topic} />
          </div>
        </div>
      </Router>
    );
  }
}

二、嵌套路由

就是说你的组件容器里面渲染出来的组件也是一个路由

也是直接上代码了

import React from "react";
import {
     
  BrowserRouter as Router,
  Route,
  Link
} from "react-router-dom";

const Category = ({
      match }) => (
  <h1>Sub Category {
     match.params.subId}</h1>
);

const SubCategory = ({
      match }) => (
  <div>
    <h1>Category {
     match.params.id}</h1>

    <ul id="menu">
      <li>
        <Link to={
     `/category/${
       match.params.id}/sub/1`}>
          Sub Category 1
        </Link>
      </li>
      <li>
        <Link to={
     `/category/${
       match.params.id}/sub/2`}>
          Sub Category 2
        </Link>
      </li>
      <li>
        <Link to={
     `/category/${
       match.params.id}/sub/3`}>
          Sub Category 3
        </Link>
      </li>
    </ul>

    <div id="page-container-2">
      <Route
        path="/category/:id/sub/:subId"
        component={
     Category}
      />
    </div>
  </div>
);


export default class NestedRoute extends React.PureComponent {
     
  render() {
     
    return (
      <Router>
        <div>
          <ul id="menu">
            <li>
              <Link to="/category/1">Category 1</Link>
            </li>
            <li>
              <Link to="/category/2">Category 2</Link>
            </li>
            <li>
              <Link to="/category/3">Category 3</Link>
            </li>
          </ul>

          <div id="page-container">
            <Route
              path="/category/:id"
              component={
     SubCategory}
            />
          </div>
        </div>
      </Router>
    );
  }
}

参考文档:https://6n20nrzlxz.codesandbox.io/

参考视频:https://time.geekbang.org/course/detail/100009301-11273?utm_source=pinpaizhuanqu&utm_medium=geektime&utm_campaign=guanwang&utm_term=guanwang&utm_content=0511

你可能感兴趣的:(React全家桶,reactjs,前端)