函數(shù)式組件
// 1.創(chuàng)建函數(shù)是組件
function MyComponent() {
console.log(this)
return <h2>我是用函數(shù)定義的組件(適用于【簡單組件】的定義)</h2>
}
// 2.渲染組件到頁面
ReactDOM.render(<MyComponent/>,document.getElementById('test'))
函數(shù)式組件中this是undefined,需注意。
1.React解析組件標簽呈枉,找到了MyComponent組件趁尼;
2.發(fā)現(xiàn)組件是使用函數(shù)定義的,隨后調(diào)用該函數(shù)猖辫,將返回的虛擬dom轉(zhuǎn)為真實dom酥泞,渲染在頁面。
類式組件
// 1.創(chuàng)建類式組件
class MyComponent extends React.Component {
render() {
console.log('render中的this:',this)
//render是放在哪里的啃憎?—— MyComponent的原型對象上芝囤,供實例使用。
//render中的this是誰辛萍?—— MyComponent的實例對象 <=> MyComponent組件實例對象悯姊。
return <h2>我是用類定義的組件(適用于【復(fù)雜組件】的定義)</h2>
}
}
// 2.渲染組件到頁面
ReactDOM.render(<MyComponent/>,document.getElementById('test'))
1.React解析組件標簽,找到了MyComponent組件;
2.發(fā)現(xiàn)組件是使用類定義的贩毕,隨后new出來該類的實例悯许,并通過該實例調(diào)用到原型上的render方法;
3.將render返回的虛擬dom轉(zhuǎn)為真實dom,渲染在頁面辉阶。