2017-07-25 68 views
0

我正在努力從我的路由器傳遞道具到我的佈局文件,但道具customClass未被傳遞。如何將道具從React Router 4傳遞給容器?

這是我作出反應的應用程序的路由器:

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

我在這裏做錯了什麼?

感謝

回答

1

好所以props參數從路由器傳遞給渲染方法回調不包含您應用到<WithMainLaout />的屬性,它包含歷史,位置,並且匹配。要解決您的問題,您可以執行以下操作:

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

這會給你兩個屬性。

+0

非常有用,它的工作原理。謝謝 – AnApprentice

+1

非常歡迎!很高興你解決了:) –

0

通道具下來是這樣的:

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

對不起。那是什麼? – AnApprentice

+0

創建各種錯誤 – AnApprentice

相關問題