1.理解
- 每個組件對象都會有props(properties)屬性
- 組件標(biāo)簽的所有屬性都保存的props
2.作用
- 通過標(biāo)簽屬性從組件外向組件內(nèi)傳遞變化的數(shù)據(jù)
- 注意:組件內(nèi)部不要修改props數(shù)據(jù)
3.編碼實現(xiàn)
- 內(nèi)部讀取某個屬性值
this.props.name
- 對props中的屬性值進(jìn)行類型限制和必要性限制
需要引入prop-types庫
Person.propTypes = {
name:Proptypes.string.isRequired,
age:Proptypes.number
}
- 擴(kuò)展屬性:將對象的所有屬性通過props傳遞
<Person {...person}/>
- 默認(rèn)屬性值:
Person.defaultProps = {
age:18
sex:"male"
}
- 組件類的構(gòu)造函數(shù)
constructor(props){
super(props)
console.log(props)//打印所有屬性
}
4.完整實現(xiàn)
//1.創(chuàng)建組件
class Person extends React.Component{
//對props進(jìn)行限制(需先引入依賴包)爹袁,傳入的類型不符合限制械荷,會出warning
// 加static關(guān)鍵字會將屬性加在類本身上阵苇,不加會寫在類的實例對象上
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 用大括號是引用了js語法,如果直接傳數(shù)值而不加大括號闷板,react無法識別
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 ("俺會說話")
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者