React元件屬性類 propTypes

2021-07-09 15:05:06 字數 1526 閱讀 6022

// 可以宣告 prop 為指定的 js 基本型別。預設

// 情況下,這些 prop 都是可傳可不傳的。

optionalarray: react.proptypes.array,

optionalbool: react.proptypes.bool,

optionalfunc: react.proptypes.func,

optionalnumber: react.proptypes.number,

optionalobject: react.proptypes.object,

optionalstring: react.proptypes.string,

// 所有可以被渲染的物件:數字,

// 字串,dom 元素或包含這些型別的陣列。

optionalnode: react.proptypes.node,

// react 元素

optionalelement: react.proptypes.element,

// 用 js 的 instanceof 操作符宣告 prop 為類的例項。

optionalmessage: react.proptypes.instanceof(message),

// 用 enum 來限制 prop 只接受指定的值。

optionalenum: react.proptypes.oneof(['news', 'photos']),

// 指定的多個物件型別中的乙個

optionalunion: react.proptypes.oneoftype([

react.proptypes.string,

react.proptypes.number,

react.proptypes.instanceof(message)

]),// 指定型別組成的陣列

optionalarrayof: react.proptypes.arrayof(react.proptypes.number),

// 指定型別的屬性構成的物件

optionalobjectof: react.proptypes.objectof(react.proptypes.number),

// 特定形狀引數的物件

optionalobjectwithshape: react.proptypes.shape(),

// 以後任意型別加上 `isrequired` 來使 prop 不可空。

requiredfunc: react.proptypes.func.isrequired,

// 不可空的任意型別

requiredany: react.proptypes.any.isrequired,

// 自定義驗證器。如果驗證失敗需要返回乙個 error 物件。不要直接

// 使用 `console.warn` 或拋異常,因為這樣 `oneoftype` 會失效。

customprop: function(props, propname, componentname)

}

React元件通訊 REF屬性

乙個 ref 例項在建構函式中建立,並賦值給 this.firstref this.firstref react.createref 等同於 在 render 方法內部,將建構函式中建立的 ref 傳遞給 div 處理dom元素 this.firstref.current dom元素.this.例項...

React元件實現越級傳遞屬性

import react,from react import proptypes from prop types 引入屬性校驗 父元件 getchildcontexttypes 1.在 父元件中,定義乙個 getchildcontext 的函式,返回乙個物件,這個物件就是要共享給 所有子孫自建的資料...

react 操作元件上的屬性

import react from react var arr class component1 extends react.component 匯出元件 export default component1 import react from react import reactdom from r...