2017-08-07 101 views
0

我有一個數組對象被傳遞作爲道具的陣列看起來像:PropTypes驗證陣列

[ 
    { 
    "title": "eat food" 
    }, 
    { 
    "title": "Drinks", 
    "sub_items": [ 
     { 
     "title": "Beer", 
     "isDrinking": true 
     } 
    ] 
    }, 
    { 
    "title": "eat Pizza" 
    }, 
    { 
    "title": "Other Drinks", 
    "sub_items": [ 
     { 
     "title": "Soda", 
     "isDrinking": false 
     }, 
     { 
     "title": "Soda", 
     "isDrinking": false 
     } 
    ] 
    } 
] 

我想要做的就是添加了propTypes驗證,像

標題:PropTypes.string .isRequired

分項目:PropTypes.array

分項目:道具陣列內部驗證諸如標題螫和isDrinking布爾值。

注意如何在一個數組上實現這一點。 (PS。我reactjs知識很有限,所以原諒我,如果我問一個明顯愚蠢的問題)

+1

[React proptype array with shape]可能的重複(https://stackoverflow.com/questions/32325912/react-proptype-array-with-shape) –

回答

1

你可以寫:

PropTypes.arrayOf(PropTypes.shape({ 
    title: PropTypes.string.isRequired, 
    sub_items: PropTypes.arrayOf(PropTypes.shape({ 
    title: PropTypes.string.isRequired, 
    isDrinking: PropTypes.bool.isRequired 
    }) 
})).isRequired 

通知sub_items怎麼不是必需的,但如果它被包含在一個的對象,它必須是定義了titleisDrinking的對象數組。