如何将道具从 React Router 4 传递到容器?

How to pass props from React Router 4 to a Container?

我正在努力将道具从我的路由器传递到我的布局文件,但道具 customClass 没有被传递。

这是我的 React 应用程序的路由器:

const WithMainLayout = ({component: Component, ...more}) => {
  return <Route {...more} render={props => {
    return (
      <MainLayout {...props}>
        <Component {...props} />
      </MainLayout>
    );
  }}/>;
};

const App = ({store}) => {
  return (
    <StoreProvider store={store}>
      <ConnectedRouter history={history}>
        <ScrollToTop>
          <Switch>
            <WithMainLayout exact path="/" component={Home2} customClass="XXX" />
          </Switch>
        </ScrollToTop>
      </ConnectedRouter>
    </StoreProvider>
  );
};

问题 在 MainLayout 中,我没有得到 customClass 道具:

class MainLayout extends React.Component {
  componentDidMount() {
    console.log(this.props.customClass);
  ...

这被记录为 undefined

我做错了什么?

像这样传递道具:

<WithMainLayout exact path="/" component={<Home2 customClass={"XXX"} />} />

好的,所以从路由器传递到渲染方法回调的 props 参数不包含您应用到 <WithMainLaout /> 的属性,它包含历史记录、位置和匹配项。要解决您的问题,您可以执行以下操作:

const WithMainLayout = ({component: Component, ...more}) => {
  return <Route {...more} render={props => {
    return (
      <MainLayout {...props} {...more}>
        <Component {...props} {...more} />
      </MainLayout>
    );
  }}/>;
};

这将为您提供两者的属性。