将道具传递给数组中的子对象

Pass props to child objects in array

我的应用程序路由是一个映射到内部的数组 <Router> 这似乎是一种常见的方法。我想将一些额外的道具传递给 <Component />。当我明确命名道具时,它被传递给 <Component /> 我可以使用它,但是,当我传播道具时,它在 <Component />.

中未定义

我需要传播道具,因为我想在以后通过其他道具,不想明确命名App.js中的所有道具。

如何确保 <Component /> 从 ``routes``` 接收 props 而无需明确命名 props?

我的代码:

当我展开道具时,它们不会传递给子组件:

const routes = [
    {
      type: PublicRoute,
      path: "/login",
      component: LoginForm,
      register: true, // I want to pass this prop
    }
  ]
  
<Router history={history}>
    <Switch>
        {routes.map((route, i) => {
            const RouteType = route.type;
            const Component = route.component;
            const Dashboard = dashboard;
            return (
            <Route
                key={i}
                path={route.path}
                exact
                render={(props) => (
                <RouteType role={route.role}>
                    <Dashboard>
                      <Component {...props} /> // register not passed
                    </Dashboard>
                </RouteType>
                )}
            />
            );
        })}
    </Switch>
</Router>

如果我命名道具(注册),它会很好地传递给子组件:

const routes = [
    {
      type: PublicRoute,
      path: "/login",
      component: LoginForm,
      register: true, // I want to pass this prop
    }
  ]

<Router history={history}>
    <Switch>
        {routes.map((route, i) => {
            const RouteType = route.type || Fragment;
            const Component = route.component;
            const Dashboard = dashboard;
            return (
            <Route
                key={i}
                path={route.path}
                exact
                render={(props) => (
                <RouteType role={route.role}>
                    <Dashboard>
                      <Component register={route.register} /> // register is passed ok
                    </Dashboard>
                </RouteType>
                )}
            />
            );
        })}
    </Switch>
</Router>

谢谢。

你可以这样通过

<Component {...route, ...props} />