记录自己项目中写的内容
路由入口是一个组件, 路由出口用Switch包着,大概如下
<TopNavigationBarWithRoute
routePath={this.state.routePath}
/>
<Switch>{this.renderAllRoutes()}</Switch>
//我们看一下 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<ITopNavigationBarProps> {
constructor(props: ITopNavigationBarProps) {
super(props);
}
public render() {
return (
<>
<Link to={routePath.a}>
a
</Link>
<Link to={routePath.b}>
b
</Link>
<Link to={routePath.c}>
c
</Link>
<Link to={routePath.d}>
d
</Link>
</>
)}
}
//要加上withRouter, 这样才能完整接收父组件传来的路由参数
export const TopNavigationBarWithRoute = withRouter<any, React.ComponentClass<ITopNavigationBarProps>>(
TopNavigationBar
);
renderAllRoutes长这样
private renderAllRoutes(): JSX.Element[] {
const routes = [];
const a= (<Route key="render-a" path={this.state.routePath.a}>组件a</Route>);
routes.push(a);
const b= (<Route key="render-b" path={this.state.routePath.b}>组件b</Route>);
routes.push(b);
const c= (<Route key="render-c" path={this.state.routePath.c}>组件c</Route>);
routes.push(c);
//d组件里面放二级路由
const d= (
<Route key="render-d" path={this.state.routePath.d}>
<TestDWithRoute
routePath={this.state.routePath}
/>
</Route>
);
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<ITestDProps> {
public render() {
const {routePath} = {...this.props};
return (
<>
<Link to={routePath.e}>e</Link>
<Link to={routePath.f}>f</Link>
<Switch>
<Route exact={true} path={routePath.e}>组件e</Route>
<Route exact={true} path={routePath.f}>组件f</Route>
//点击link d, 跳转到e, 这里的this.props.location.pathname就是当前路由
{this.props.location.pathname === routePath.d? (
<Route>
<Redirect to={routePath.e} />
</Route>
) : null}
</Switch>
</>
);
}
}
//最后不要忘记加withRouter
export const TestDWithRoute= withRouter<any, React.ComponentClass<ITestDProps>>(TestD);
我是把自己项目中的内容简化,如果有问题欢迎指教