組件
1.注意事項
- 組件內部定義的所有方法應該是組件實例對象的(this)
- 組件的內置方法的this指向實例對象名扛,自定義方法的this指向null
針對上面所說的2點,我舉一個很簡單的例子:
constructor(props) {
super(props)
this.state = {
msg: 'atguigu'
}
this.handleChange = this.handleChange.bind(this)
}
這里的this就是組件的實例對象稼病,這里為什么要用bind,不用call和apply掖鱼,是因為bind是綁定后然走,返回一個函數(shù)。bing 返回的是一個新的函數(shù)戏挡,你必須調用它才會被執(zhí)行芍瑞。
然而call和apply是直接就調用了。
- 腳手架中可以利用箭頭函數(shù)
2.定義組件的方法
- 工廠函數(shù)式(無狀態(tài)--簡單組件)
function Welcome1(props) {
return <h2>工廠函數(shù)式創(chuàng)建的組件</h2>
}
* 使用props屬性對象的時候可以通過形參獲取
- ES6的class類的方法(有狀態(tài)--較為復雜組件)
class Welcome2 extends React.Component{
render(){
console.log(this instanceof Welcome2, this);
return <h3>ES6的類class創(chuàng)建的組件</h3>
}
}
* 注意繼承react核心組件庫
- ES5的老語法(了解即可)
var Welcome3 = React.createClass({
render () {
return <h1>ES5D的老語法</h1>
}
})褐墅;