ts+react路由react-router-dom

记录自己项目中写的内容

路由入口是一个组件, 路由出口用Switch包着,大概如下

        
        {this.renderAllRoutes()}

//我们看一下  this.state.routePath
    const routePath: IRoutePath = {
      a: "/a",
      b: "/b",
      c: "/c",
      d: "/d",
      e: "/d/e",
      f: "/d/f",
    };


/** path of router */
export interface IRoutePath {
  a: string;
  b: string;
  c: string;
  d: string;
  e: string;
  f: string;
}

 

然后我们看看TopNavigationBarWithRoute

//重要的是引入  withRouter,  RouteComponentProps,  使组件能接收父组件传来的路由参数
import {Link, withRouter, RouteComponentProps} from "react-router-dom";

// 在你组件的Prop中 加入  extends RouteComponentProps
//this.props就有history,  location 和 match,  this.props.location.pathname就是当前的路由值
export interface ITopNavigationBarProps extends RouteComponentProps {
  /** all router  */
  routePath: IRoutePath;
}


export class TopNavigationBar extends React.Component {
  constructor(props: ITopNavigationBarProps) {
    super(props);
  }
  public render() {
    return (
        <>
          
            a
          
          
          
            b
          

          
            c
          
          
            d
          
        
    )}
}

//要加上withRouter, 这样才能完整接收父组件传来的路由参数
export const TopNavigationBarWithRoute = withRouter>(
  TopNavigationBar
);

renderAllRoutes长这样

 private renderAllRoutes(): JSX.Element[] {
    const routes = [];
    const a= (组件a);
    routes.push(a);
    const b= (组件b);
    routes.push(b);
    const c= (组件c);
    routes.push(c);
    //d组件里面放二级路由
    const d= (
      
        
      
    );
    routes.push(d);
    return routes;
  }

最后我的TestDWithRoute组件长这样

import {Link, Route, Switch, Redirect, withRouter, RouteComponentProps} from "react-router-dom";

//在组件的Prop接口中加 extends  RouteComponentProps 
export interface ITestDProps extends RouteComponentProps {
  // all router
  routePath: IRoutePath;
}

export class TestD extends React.Component {
 public render() {
    const {routePath} = {...this.props};
    return (
        <>
          e
          f
          
              组件e
              组件f
                //点击link d, 跳转到e,  这里的this.props.location.pathname就是当前路由
              {this.props.location.pathname === routePath.d? (
                
                  
                
              ) : null}
            
        
    );
  }
}

//最后不要忘记加withRouter
export const TestDWithRoute= withRouter>(TestD);

我是把自己项目中的内容简化,如果有问题欢迎指教

你可能感兴趣的:(react)