## 六、PropTypes
組件的屬性可以接受任意值,字符串、對象、函數等等都可以。有時,我們需要一種機制,驗證別人使用組件時,提供的參數是否符合要求。
組件類的PropTypes屬性,就是用來驗證組件實例的屬性是否符合要求(查看?[demo06](https://github.com/ruanyf/react-demos/blob/master/demo06/index.html))。
> ~~~
> 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;
>
> React.render(
> <MyTitle title={data} />,
> document.body
> );
> ~~~
這樣一來,title屬性就通不過驗證了。控制臺會顯示一行錯誤信息。
> ~~~
> Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.
> ~~~
更多的PropTypes設置,可以查看[官方文檔](http://facebook.github.io/react/docs/reusable-components.html)。
此外,getDefaultProps 方法可以用來設置組件屬性的默認值。
> ~~~
> var MyTitle = React.createClass({
> getDefaultProps : function () {
> return {
> title : 'Hello World'
> };
> },
>
> render: function() {
> return <h1> {this.props.title} </h1>;
> }
> });
>
> React.render(
> <MyTitle />,
> document.body
> );
> ~~~
上面代碼會輸出"Hello World"。