4.5.Data flow: prop vs. prop.children, state
prop: property的縮寫
1.this.prop:
指定單一個由上層元件所傳入的參數, 需寫在標籤內 (字串符)
2.this.prop.children
上層元件所傳入的參數陣列, 寫在標籤的內容中
3.propTypes:
propTypes 使用來規範元件Props的型別與必需狀態
當父元件沒有提供props的屬性時,可以採用getDefaultProps,
預設props屬性的方式,讓元件使用預設的設定值,確保有props帶入。
React.PropTypes 的種類:
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) // 具有某種屬性類型的物件(字串類型)
React.PropTypes.shape({ // 是否符合指定格式的物件
color: React.PropTypes.string,
fontSize: React.PropTypes.number
});
React.PropTypes.any.isRequired // 可以是任何格式,且必要。
state與props的差別是在於state只存在組件的內部
this.state -> 同層物件
1.this.setState
setState is done to 'set' the state of a value, even if its already set
in the 'getInitialState' function.
2.this.replaceState
The replaceState() method is for when you want to clear out the values
already in state, and add new ones.
this.props -> 上層物件
reference:
Last updated
Was this helpful?