2017-02-10 47 views
3

我们已经知道,如何设置一个defaultProps。如何设置对象类型的React默认道具

TestComponent.defaultProps = { 
    isTest: true 
}; 

但我经常使用道具作为对象类型。

在家长,

render(){ 
    let sample = { 
     isTest : true, 
     isLoggedIn : true 
    } 
    return (
     <div> 
      <TestComponent sample = {sample} /> 
     </div> 
    ) 
} 

在子组件,我想设置isLoggedInfalse为默认值。如果没有设置(或不从父母传给)isLoggedIn,默认值是true

但我不知道如何设置defaultProps为object type

TestComponent.defaultProps = { 
    sample : { 
     isLoggedIn: false 
    } 
}; 

如何做到这一点?

+0

这是不可能的“传统”的意思。您必须设置一个手动执行此检查的功能。我在几个月前回答了一个类似的问题。我会在下面链接它。 – Chris

+1

可能重复的[如何在React中检测对象prop的属性?](http://stackoverflow.com/questions/40300016/how-to-typecheck-properties-of-an-object-prop-in-react) – Chris

回答

2

您的代码

TestComponent.defaultProps = { 
    sample : { 
    isLoggedIn: false 
    } 
}; 

应该工作。

进行型式验证(propTypes),使用React.PropTypes.shape嵌套对象道具这样的:

React.PropTypes.shape({ 
    isLoggedIn: React.PropTypes.bool 
}) 

请参阅文档:https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes

+0

它看起来类型检查。有没有办法在对象类型中设置默认道具? –

+0

你的代码应该可以工作,不是吗? – CodinCat

+0

看到这个例子http://codepen.io/CodinCat/pen/jyQbxB?editors=1010 – CodinCat

0

我已经找到了一种解决方法是:

在组件声明之前,声明你的默认道具。 在渲染方法中,检查是否提供了prop?如果不是,则用defaultprops替换它。

这里是工作示例:

imports........... 

const defaultProps: { 
    sample: { 
     isLoggedIn: false 
     //you can have any number of props here 
    } 
} 

class MyClass extends Component { 
    render() { 
     Object.entries(defaultProps).map(prop => this.props.sample[prop[0]] = this.props.sample[prop[0]] ? this.props.sample[prop[0]] : defaultProps[prop[0]]); 
     return (
      <div> 
       ........... 
      </div> 
     ); 
    } 
} 

export default class MyClass;