這篇沒什麼難度,但因為身邊誘惑太多居然寫了一個月

以下直接開始了

我們在使用React元件的時候常常會透過 props 來傳遞參數

但是當元件越來越複雜時,傳入參數值的正確性就變得很重要了

所以 React.PropTypes 就提供了多組驗證器來規範參數值的型別與狀態

如果傳入的 props 被驗證為不合法時就會在 javascript console 拋出警告

然後因為考量到效能問題,所以只會在開發環境觸發驗證 React.PropTypes

所以不用擔心會影響到正式服務,其實就跟 debugger 關鍵字一樣,是在 console 使用的

用以下這個例子來看一下

var Student = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
age: React.PropTypes.number
},
render: function () {
return (
<div>
name:{ this.props.name } <br />
age: { this.props.age }
</div>
)
}
});
ReactDOM.render(
<Student name="eason" age="18" gender="male" />,
document.getElementById('example')
);

 

像上面的例子,在 propTypes 規定傳入的 age 參數必須要是 number 型態

所以使用的時候傳入字串 age="18" ( 傳入型別 number 要這樣寫 age={18} )

打開 console 看就會看到驗證錯誤的警告

Warning: Failed propType: Invalid prop `age` of type `string` supplied to `Student`, expected `number`.

但其實不影響到實際的執行,警告訊息只有在 console 看的到

使用方式就如上面範例一樣簡單,然後可以使用的驗證類型有這些

Basic types

React.PropTypes.string   (字串)

React.PropTypes.number   (數字)

React.PropTypes.object     (物件)

React.PropTypes.func     (函數)

React.PropTypes.bool    (布林)

React.PropTypes.any   (可以為任意的類型)

Required types

(所有驗證,只要在後面加上 .isRequired 就會變成必要輸入項目,像下面這樣)

React.PropTypes.func.isRequired 

React.PropTypes.any.isRequired

React elements

React.PropTypes.element  (要是 react 的元素)

React.PropTypes.node     (numbers, strings, elements 或者任何這種類型的陣列)

Enumerables

React.PropTypes.oneOf(['M','F'])   (其中一個,以這個例子來講,必須要是 'M' or 'F' 其中一個)

React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number ])

(其中一種類型,以上面的例子來看,必須要是 string or number 其中一種)

Arrays and objects

React.PropTypes.array    (陣列)

React.PropTypes.arrayOf(React.PropTypes.number)  (是指定類型組成的陣列,此例是 number)

React.PropTypes.object  (物件)

React.PropTypes.objectOf(React.PropTypes.number)  (有某種屬性類型的物件)

React.PropTypes.instanceOf(Message)  (某種類別的實體,此例而言類別名稱是 Message)

React.PropTypes.shape ({     (指定格式的物件,此例而言要有 color、size 屬性)
    color:  React.PropTypes.string,
    size:   React.PropTypes.number
})

Custom validation

function(props, propName, componentName) {    (自訂驗證)
   if (!/matchme/.test(props[propName])) {
      return new Error('Validation failed!');
   }
}

 

設定預設的 props 

可以使用 getDefaultProps 來設定預設的 props,像下面這樣

var MyTitle = React.createClass({
getDefaultProps : function () {
return {
title : 'Hello World'
};
},
render: function() {
return <h1> {this.props.title} </h1>;
}
});

 

參考資料:

http://ricostacruz.com/cheatsheets/react.html

https://facebook.github.io/react/docs/reusable-components.html

 

快快樂樂學 React  系列

=========================================

React 初學者筆記與教學 (一) - 新手村搞定開發環境

React 初學者筆記與教學 (二) - Virtual DOM、Component (元件) 的建立與傳值

React 初學者筆記與教學 (三) - State 的介紹與使用方式,讓你的元件可以跟使用者互動!

React 初學者筆記與教學 (四) - 使用 React.PropTypes 來驗證元件屬性

 

 

arrow
arrow
    全站熱搜

    小雕 發表在 痞客邦 留言(0) 人氣()