propTypes 使用來規範元件Props的型別與必需狀態
var Test = React.createClass({ propTypes: { // required requiredFunc: React.PropTypes.func.isRequired, requiredAny: React.PropTypes.any.isRequired, // primitives, optional by default bool: React.PropTypes.bool, func: React.PropTypes.func, number: React.PropTypes.number, string: React.PropTypes.string, }, render:function(){ return <div/> } }); var component = React.render( <Test requiredFunc="bar" bool="true" requiredAny="a"/>, document.body );
若沒有按照規範,會顯示警告
線上測試:http://jsbin.com/suweke/3/edit
React.PropTypes.array // 陣列 React.PropTypes . bool . isRequired // Boolean 且必要。 React . PropTypes . func // 函式 React . PropTypes . number // 數字 React . PropTypes . object // 物件 React . PropTypes . string // 字串 React . PropTypes . node // 任何類型的: numbers, strings, elements 或者任何這種類型的陣列 React . PropTypes . element // React 元素 React . PropTypes . instanceOf ( XXX ) // 某種XXX類別的實體 React . PropTypes . oneOf ([ 'foo' , 'bar' ]) // 其中一個字串 React . PropTypes . oneOfType ([ React . PropTypes . string , React . PropTypes . array ]) // 其中一種格式類型 React . PropTypes . arrayOf ( React . PropTypes . string ) // 某種類型的陣列(字串類型) React . PropTypes . objectOf ( React . PropTypes . string
名称(*)