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
感謝您的回答!僅供參考,返回語句可以簡單地爲'return extendedChild;'(不帶括號括起來) –
我很高興我可以幫助:)您是對的,謝謝!答案已更新。 –
只是一個快速的:克隆後,將'孩子'垃圾收集?內存使用方面有什麼問題嗎? –