2017-02-10 42 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; 
相關問題