1.理解
- 每個(gè)組件對(duì)象都會(huì)有props(properties)屬性
- 組件標(biāo)簽的所有屬性都保存的props
2.作用
- 通過(guò)標(biāo)簽屬性從組件外向組件內(nèi)傳遞變化的數(shù)據(jù)
- 注意:組件內(nèi)部不要修改props數(shù)據(jù)
3.編碼實(shí)現(xiàn)
- 內(nèi)部讀取某個(gè)屬性值
this.props.name
- 對(duì)props中的屬性值進(jìn)行類型限制和必要性限制
需要引入prop-types庫(kù)
Person.propTypes = {
name:Proptypes.string.isRequired,
age:Proptypes.number
}
- 擴(kuò)展屬性:將對(duì)象的所有屬性通過(guò)props傳遞
<Person {...person}/>
- 默認(rèn)屬性值:
Person.defaultProps = {
age:18
sex:"male"
}
- 組件類的構(gòu)造函數(shù)
constructor(props){
super(props)
console.log(props)//打印所有屬性
}
4.完整實(shí)現(xiàn)
//1.創(chuàng)建組件
class Person extends React.Component{
//對(duì)props進(jìn)行限制(需先引入依賴包),傳入的類型不符合限制,會(huì)出warning
// 加static關(guān)鍵字會(huì)將屬性加在類本身上,不加會(huì)寫在類的實(shí)例對(duì)象上
static propTypes = {
age: PropTypes.number,
name : PropTypes.string.isRequired,
speak : PropTypes.func
}
//指定默認(rèn)的標(biāo)簽屬性值
static defaultProps = {
sex:"不男不女",
age:18
}
//render方法
render(){
const{name,age,sex}= this.props
return(
<ul>
<li>姓名:{name}</li>
<li>性別:{sex}</li>
<li>年齡:{age+1}</li>
</ul>
)
}
}
// 2.渲染
// 此處的年齡18 用大括號(hào)是引用了js語(yǔ)法,如果直接傳數(shù)值而不加大括號(hào),react無(wú)法識(shí)別
ReactDOM.render(<Person name= "jerry" age= {18} sex="male" speak = {speak}/>,document.getElementById("test"))
const p = {name: "Lily",age:18,sex:"female"}
ReactDOM.render(<Person {... p }/>,document.getElementById("test2"))
function speak() {
console.log ("俺會(huì)說(shuō)話")
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。