如何将props从react-router Switch语句传递到组件

时间:2018-12-06 15:12:48

标签: reactjs react-router

我有一个简单的数组,其中包含可能的路线,然后在map react-dom-router组件中<Switch>将它们<Switch>显示出用户所处的正确路线。

我的问题是: 如何将道具从路线对象传递到someKey中正在使用的组件?这里要讨论的关键是/faq路线中的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" } ]; 道具。

route.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;

Body.js

FaqPage

我尝试了几种建议的方法,但是无法访问this.props.someKey组件中的道具。在该组件内部,我尝试将prop与<Route />之类的语句一起使用时没有运气。我看到的每个样本都在Java::dice.Dice 内使用硬编码组件,但我使用的是变量。

https://github.com/ReactTraining/react-router/issues/4105#issuecomment-291834881 https://github.com/ReactTraining/react-router/issues/4627#issuecomment-332972317

您知道我应该怎么做才能做到这一点吗?

2 个答案:

答案 0 :(得分:2)

您可以将组件包装到render函数中。

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(({component: Cmp, ...route}, i) => {
                        // HOW DO I PASS THE 'someKey' PROP HERE?
                        return (<Route
                                 key={i}
                                 {...route}
                                 render={props => <Cmp {...props} someKey="someValue" />} 
                               />);
                    })}
                </Switch>
            </div>
        );
    }
}

export default Body;

答案 1 :(得分:0)

尝试将渲染功能添加到Body.js中的Route Component中,然后在其中访问该组件-

class Body extends Component {
    render() {
        return (
            <div className="main-body">
                <Switch>
                    {routes.map(({component: ComponentDetails, ...route}, i) => {
                        // HOW DO I PASS THE 'someKey' PROP HERE?
                        return (
                               <Route 
                                exact path='/'
                                key={i} 
                                {...route}
                                render={(props)=>
                                 <ComponentDetails {...props}
                                   someKey="TEST"  />)
                </Switch>
            </div>
        );
    }
}

export default Body;