傳值:
使用props接收組件的自定義屬性,這個接收是類組件自動接收的,在類組件的this中,包含有props這個對象,組件的自定義屬性會被收集到這個對象中,那么在類組件中就可以使用this.props獲得這個對象保存的值,從而進行邏輯或者相關操作。
舉例如下:
//定義 類 組件
class Ae3 extends Component { render() { // 打印this對象
console.log(this) // 使用傳過來的id值
return <div id={this.props.id}>hello React</div>
} }
export default Ae3
{/* 調用類組件,並傳入值,及自定義屬性id */} <Ae3 id={id}></Ae3>
打印this得到的結果:
可以看到,有props屬性,而我們傳過去的值就保存在這里,並且還可以看到,有state屬性,這說明類組件自身有這個跟屬性,並且該屬性為null,這是因為我們沒有使用state的原因。
私有屬性,state,類似於vue中的data:
看代碼
//定義 類 組件
class Ae3 extends Component { constructor(props) { // 打印接收到的值
console.log(props) // 調用父類的構造方法,並得到this
super() console.log('------分界線-------') // 打印this
console.log(this) // 打印this中的props屬性
console.log(this.props) // 私有屬性state的定義聲明或者叫初始化
this.state = { id: 1 } } render() { // 打印this對象
console.log(this) // 使用傳過來的id值
return <div id={this.state.id+"xxxxxxxxxx"+this.props.id}>hello React</div>
} }
export default Ae3
調用組件:
{/* 調用類組件,並傳入值,及自定義屬性id */} <Ae3 id={id}></Ae3>
接下來,看打印結果:
但在render方法中打印的this是可以使用的。
導致構造方法中的this是undefined的是因為,super方法只是得到this,想要使用其屬性,必須要給super方法傳參,操作如下:
這樣就好了,這就是給super方法傳參的原因,是為了得到完整且可用的this。
得到完整且可用的構造函數中的(再次強調這是 構造函數 中的this)this后能干嘛?
答:能初始化state中的值:
// 私有屬性state的定義聲明或者叫初始化
this.state = { // 給私有屬性賦值接收過來的值
id: this.props.id //這時候這么調用this以及this中的屬性就不會出現undefined的情況了 }
有關 setState的使用,只有這兩個場景下才能使用:
1:構造函數中,用來初始化。
2:自定義函數和鈎子函數中,作用:用來更新或者改變state屬性。
關於ES6類的繼承和this以及props的相關問題,請看:https://www.cnblogs.com/zqblog1314/p/12902707.html
export
default
Ae3