2017-03-22 93 views
1

這是我的目標。我想創建一個複合組件,它會在顯示children元素之前檢查匹配的url的有效性。否則,它將返回一個公共組件以顯示錯誤消息。如何將額外的屬性傳遞給reactjs中的子元素?

因此,這裏是我的我的「裝飾」的代碼:

const EnforceUrlValidation = (test, children) => { 
    const fn = ({ match }) => { 
    if (! test(match)) { 
     return (<InvalidUrlContainer />); 
    } 
    return ({children}); 
    } 
    return fn; 
} 

這是它是如何在我的路由器使用:

const WelcomePage = EnforceUrlValidation(
    (match) => { 
     const articleId = match.params.articleId; 
     return articleId && isValidarticleId(articleId); 
    } 
    , <WelcomeContainer/> 
) 
... 
<Routers> 
    <Switch> 
      <Route 
       path="/:articleId" 
       component={WelcomePage} 
      /> 
... 

</Routers> 

我現在的問題是,我還是想將match對象轉換爲EnforceUrlValidation內部的children。我怎樣才能做到這一點?

嘗試1

const EnforceUrlValidation = (test, children) => { 
    const fn = ({ match }) => { 
    if (! test(match)) { 
     return (<InvalidUrlContainer />); 
    } 
    return (<children match={match} />); 
    } 
    return fn; 
} 

children沒有在這種情況下呈現。

嘗試2

const EnforceUrlValidation = (test, children) => { 
    const fn = ({ match }) => { 
    if (! test(match)) { 
     return (<InvalidUrlContainer />); 
    } 
    return (
     <div match={match} >{children} </div> 
    ) 
    } 
    return fn; 
} 

它失敗,因爲div不支持match

回答

7

您可以使用React.cloneElement添加屬性孩子:

const EnforceUrlValidation = (test, children) => { 
    const fn = ({ match }) => { 
    if (! test(match)) { 
     return (<InvalidUrlContainer />); 
    } 
    const extendedChild = React.cloneElement(children, {match: match}); 
    return extendedChild; 
    } 
    return fn; 
} 
+0

感謝您的回答!僅供參考,返回語句可以簡單地爲'return extendedChild;'(不帶括號括起來) –

+0

我很高興我可以幫助:)您是對的,謝謝!答案已更新。 –

+0

只是一個快速的:克隆後,將'孩子'垃圾收集?內存使用方面有什麼問題嗎? –

相關問題