我们已经知道,如何设置一个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