1、組件化定義
整個(gè)邏輯其實(shí)可以看做一個(gè)整體不从,那么我們就可以將其封裝成一個(gè)組件:
我們說(shuō)過(guò)ReactDOM.render第一參數(shù)是一個(gè)HTML原生或者一個(gè)組件惜姐;
所以我們可以先將之前的業(yè)務(wù)邏輯封裝到一個(gè)組件中,然后傳入到ReactDOM.render函數(shù)中的第一個(gè)參數(shù)椿息;
在React中歹袁,如何封裝一個(gè)組件呢?
這里我們暫時(shí)使用類的方式封裝組件:
- 1.定義一個(gè)類(類名大寫(xiě)寝优,組件的名稱是必須大寫(xiě)的条舔,小寫(xiě)會(huì)被認(rèn)為是HTML元素),繼承自React.Component
- 2.實(shí)現(xiàn)當(dāng)前組件的render函數(shù)ürender當(dāng)中返回的jsx內(nèi)容乏矾,就是之后React會(huì)幫助我們渲染的內(nèi)容
<div id="root" />
class App extends React.Component{
render(){
return <h1> Hello React孟抗! </h1>
}
}
React.render(<App />,doucument.getElementById('root'));
2、組件-數(shù)據(jù)依賴
在組件中的數(shù)據(jù)钻心,我們可以分成兩類:
- 參與界面更新的數(shù)據(jù):當(dāng)數(shù)據(jù)變量時(shí)凄硼,需要更新組件渲染的內(nèi)容
- 不參與界面更新的數(shù)據(jù):當(dāng)數(shù)據(jù)變量時(shí),不需要更新將組建渲染的內(nèi)容
參與界面更新的數(shù)據(jù)我們也可以稱之為是參與數(shù)據(jù)流捷沸,這個(gè)數(shù)據(jù)是定義在當(dāng)前對(duì)象的state中
我們可以通過(guò)在構(gòu)造函數(shù)中 this.state={定義的數(shù)據(jù)}
當(dāng)我們的數(shù)據(jù)發(fā)生變化時(shí)摊沉,我們可以調(diào)用this.setState來(lái)更新數(shù)據(jù),并且通知React進(jìn)行update操作
在進(jìn)行update操作時(shí)亿胸,就會(huì)重新調(diào)用render函數(shù)坯钦,并且使用最新的數(shù)據(jù),來(lái)渲染界面
class App extends React.Component{
constructor{
super();
this.state = {
message:'hello world'
}
}
}
3侈玄、組件-事件綁定
事件綁定中的this
在類中直接定義一個(gè)函數(shù),并且將這個(gè)函數(shù)綁定到html原生的onClick事件上吟温,當(dāng)前這個(gè)函數(shù)的this指向的是誰(shuí)呢序仙?
默認(rèn)情況下是undefinedp很奇怪,居然是undefined鲁豪;
因?yàn)樵谡5腄OM操作中潘悼,監(jiān)聽(tīng)點(diǎn)擊,監(jiān)聽(tīng)函數(shù)中的this其實(shí)是節(jié)點(diǎn)對(duì)象(比如說(shuō)是button對(duì)象)爬橡;
這次因?yàn)镽eact并不是直接渲染成真實(shí)的DOM治唤,我們所編寫(xiě)的button只是一個(gè)語(yǔ)法糖,它的本質(zhì)React的Element對(duì)象糙申;
那么在這里發(fā)生監(jiān)聽(tīng)的時(shí)候宾添,react給我們的函數(shù)綁定的this,默認(rèn)情況下就是一個(gè)undefined;
class App extende React.Component{
constructor(){
super();
this.bindWithConstructor = this.bindWithConstructor.bind(this);
}
function bindWithConstructor(e){
console.log(this,e);
}
arrowFunction = (e)=>{
console.log(this,e);
}
jsxFunction = (e)=>{
console.log(this,e)
}
render(){
retutn (
<>
{/* bind綁定 */}
<button onClick={this.bindWithConstructor} ></button>
{/* 箭頭函數(shù) */}
<button onClick={this.arrowFunction}></button>
{/* 監(jiān)聽(tīng)函數(shù)中添加一個(gè)調(diào)用執(zhí)行 */}
<button onClick={ (e)=>{ this.jsxFunction(e) } }></button>
</>
)
}
}
classComponent(類組件)
默認(rèn)要求
- 組件的名稱必須是大寫(xiě)
- 組件必須繼承React.Component缕陕,這個(gè)是用來(lái)區(qū)分FunctionComponent
- 組件必須實(shí)現(xiàn)render函數(shù)
render函數(shù)被調(diào)用時(shí)粱锐,會(huì)檢查this.props\this.state的變化并返回一定的內(nèi)容
1、ReactElement
一個(gè)真實(shí)DOM結(jié)點(diǎn)
一個(gè)ReactElement
2扛邑、數(shù)組或者React.Fragments
返回多個(gè)元素
3怜浅、Portals
可以渲染子結(jié)點(diǎn)渲染到其他DOM結(jié)點(diǎn)下
4、字符串或數(shù)值
在DOM中直接渲染成文本
5蔬崩、布爾類型或null
什么都不渲染
functionComponent(函數(shù)組件)
默認(rèn)要求
使用function進(jìn)行聲明恶座,返回值要求與classComponent的render的返回值是一樣的
特點(diǎn)
1、沒(méi)有生命周期
2沥阳、沒(méi)有this(沒(méi)有組件實(shí)例)
3纽帖、沒(méi)有內(nèi)部狀態(tài)(this.state)
export default function App(props){
return ( <h2> hello world </h2> )
}