組件的屬性可以接受任意值,字符串,函數,對象。有時,我們需要一種機制,驗證別人使用組件時,提供的參數是否符合要求。
組件類的 PropTypes屬性。就是驗證組件實例的屬性是否符合要求
var MyTitle = React.createClass({
propTypes:{
title:React.propTypes.string.isRequired,
}
render:function(){
return <h1>{this.props.title}</h1>
}
})
上面的MyTitle 有個title屬性。PropTypes告訴React這個title屬性是必須的。而且它的值是字符串,現在我們設置title的值是一個數值。
var data = 123
ReactDOM.render(
<MyTitle title={data}/>
document.body
)
這樣一來title就通過不了驗證,控制台會顯示一行錯誤信息。
Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`
此外 getDefaultProps 可以用來設置屬性的默認值
var MyTitle = React.createClass({
getDefaultProps: function(){
return (
title: "Hello world"
)
},
render:function(){
return <h1>{this.props.title}</h1>
}
})
ReactDOM.render({
<MyTitle />,
document.body
})