【发布时间】:2019-05-08 07:49:01
【问题描述】:
我有一个简单的数组,其中包含可能的路线,然后 map 将它们放在 react-dom-router <Switch> 组件中,以显示用户所在的正确路线。
我的问题是:
如何将路由对象中的道具传递给<Switch> 中使用的组件?这里有问题的关键是/faq 路由中的someKey 属性。
route.js
import Home from "../components/home/Home";
import FaqPage from "../components/faq/FaqPage";
export default [
{
path: "/",
exact: true,
component: Home
},
{
path: "/faq",
component: FaqPage,
someKey: "Test"
}
];
Body.js
import React, { Component } from "react";
import { Switch, Route } from "react-router-dom";
// Data
import routes from "../shared/routes";
class Body extends Component {
render() {
return (
<div className="main-body">
<Switch>
{routes.map((route, i) => {
// HOW DO I PASS THE 'someKey' PROP HERE?
return <Route key={i} {...route} />;
})}
</Switch>
</div>
);
}
}
export default Body;
我尝试了几种不同的建议方法,但我无法访问 FaqPage 组件中的道具。在该组件内部,我尝试使用带有 this.props.someKey 之类的语句的道具,但没有运气。我看到的每个示例都使用<Route /> 中的硬编码组件,但我使用的是变量。
https://github.com/ReactTraining/react-router/issues/4105#issuecomment-291834881 https://github.com/ReactTraining/react-router/issues/4627#issuecomment-332972317
知道我应该怎么做才能做到这一点吗?
【问题讨论】:
标签: reactjs react-router