我們已經知道,如何設置一個defaultProps。如何設置對象類型的React默認道具
TestComponent.defaultProps = {
isTest: true
};
但我經常使用道具作爲對象類型。
在家長,
render(){
let sample = {
isTest : true,
isLoggedIn : true
}
return (
<div>
<TestComponent sample = {sample} />
</div>
)
}
在子組件,我想設置isLoggedIn
到false
爲默認值。如果沒有設置(或不從父母傳給)isLoggedIn
,默認值是true
但我不知道如何設置defaultProps爲object type
TestComponent.defaultProps = {
sample : {
isLoggedIn: false
}
};
如何做到這一點?
這是不可能的「傳統」的意思。您必須設置一個手動執行此檢查的功能。我在幾個月前回答了一個類似的問題。我會在下面鏈接它。 – Chris
可能重複的[如何在React中檢測對象prop的屬性?](http://stackoverflow.com/questions/40300016/how-to-typecheck-properties-of-an-object-prop-in-react) – Chris