我是新来的反应。我正面临一个问题,因为添加了功能组件的子路由。
我要知道,对于类组件,我们使用的
<Router>
<Route component={Main}>
<Route path="/" component={Home}/>
<Route path="/cars" component={Car}/>
<Route path="/about" component={About}/>
</Route>
</Router>`为了在组件中访问,我们使用{this.props.children}。
请让我知道如何在功能组件中为子路由编写语法。(我用react-router-dom)。
发布于 2020-01-20 12:14:18
我建议你先读react路由器文档。
功能组件示例可以如下:
Routes.component.js
import * as React from "react";
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
const Routes = props =>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</Router>如果路由器是使用HTML5历史API与URL同步UI的BrowserRouter,则Switch将呈现与URL位置匹配的第一个子<Route>,而路由将在其路径与当前URL匹配时呈现某些UI。
Dashboard.component.js
import * as React from "react";
import {Route, Link} from "react-router-dom";
const Dashboard = ({ match }) =>
<div>
<h2>Dashboard</h2>
<div>
<ul>
<li>
<Link to={`${match.url}/projects`}>Projects</Link>
</li>
</ul>
<hr />
<Route path={`${match.path}/projects`} component={Projects} />
</div>
</div>在要嵌套另一条路由的组件中,通过在路由组件中输入另一条路由,您将在道具中获取https://reacttraining.com/react-router/web/api/match。
这样,您就可以使用它的属性:
match.url:这是从父程序收集的url的一部分,并构建了另一个<Link>子程序。match.path:用于链接和构建另一个<Route>子节点的路径我会告诉你更多关于它的在这个例子中,我创建了。你必须点击仪表板
所有这些都在React路由器文档中:)
https://stackoverflow.com/questions/59822829
复制相似问题