简体   繁体   中英

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

I'm working to pass a prop from my router to my layout file but the prop customClass is not being passed.

Here is my React app's router:

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>
  );
};

the problem In MainLayout, I'm not getting the customClass prop:

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

This is being logged as undefined .

What am I doing wrong here?

Ok so the props argument passed from router to the render method callback does not contain the properties you applied to <WithMainLaout /> , it contains history, location, and match. To fix your issue you can do the following:

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

This will give you the properties from both.

这样传递道具:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM