組件的屬性可以接受任意值,字符串、對(duì)象、函數(shù)等等都可以。有時(shí),我們需要一種機(jī)制,驗(yàn)證別人使用組件時(shí),提供的參數(shù)是否符合要求。
組件類的PropTypes屬性,就是用來驗(yàn)證組件實(shí)例的屬性是否符合要求(查看 demo06)。
var MyTitle = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,
},
render: function() {
return <h1> {this.props.title} </h1>;
}
});
上面的Mytitle組件有一個(gè)title屬性。PropTypes 告訴 React,這個(gè) title 屬性是必須的,而且它的值必須是字符串?,F(xiàn)在,我們?cè)O(shè)置 title 屬性的值是一個(gè)數(shù)值。
var data = 123;
React.render(
<MyTitle title={data} />,
document.body
);
這樣一來,title屬性就通不過驗(yàn)證了。控制臺(tái)會(huì)顯示一行錯(cuò)誤信息。
Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.
更多的PropTypes設(shè)置,可以查看官方文檔。
此外,getDefaultProps 方法可以用來設(shè)置組件屬性的默認(rèn)值。
var MyTitle = React.createClass({
getDefaultProps : function () {
return {
title : 'Hello World'
};
},
render: function() {
return <h1> {this.props.title} </h1>;
}
});
React.render(
<MyTitle />,
document.body
);
上面代碼會(huì)輸出"Hello World"。
更多建議: