這個(gè)例子是React官方文檔里面的叼架,代碼也在CodePen,例子非常簡(jiǎn)單衣撬,展示了React組件開(kāi)發(fā)的基本過(guò)程乖订,這里將這個(gè)例子進(jìn)行分析記錄,當(dāng)做學(xué)習(xí)筆記吧具练!首先看代碼:
//HTML
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
//JS
function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<FormattedDate date={this.state.date} />
</div>
);
}
}
function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
程序的運(yùn)行過(guò)程:
1乍构、在html里面定義一個(gè)div,id為root
2扛点、 調(diào)用ReactDOM.render使用App渲染id為root的div哥遮,這里會(huì)調(diào)用函數(shù)App
3、函數(shù)App返回的是什么呢占键?不是字符串昔善,也不是HTML元潘,而是JSX畔乙,JSX是JavaScript語(yǔ)法的擴(kuò)展,Babel會(huì)將JSX編譯成React.createElement()的調(diào)用翩概,這里可以簡(jiǎn)單看成返回界面布局就行了
4牲距、在函數(shù)App返回的布局中返咱,有三個(gè)Clock組件,Clock組件繼承React.Component牍鞠,當(dāng)被傳入ReactDOM.render中后咖摹,會(huì)調(diào)用Clock構(gòu)造方法
5、在Clock構(gòu)造方法可以接收一個(gè)props, 它來(lái)保存組件的組件的屬性难述,這里并沒(méi)有傳入任何屬性值萤晴,在構(gòu)造方法里面初始化組件的狀態(tài)state,給狀態(tài)設(shè)置了date字段
6胁后、接下來(lái)會(huì)調(diào)用Clock的render方法來(lái)渲染組件店读,render方法也是返回了JSX,里面有Hello World的標(biāo)題攀芯,并且調(diào)用FormattedDate函數(shù)屯断,傳入?yún)?shù)date,返回時(shí)間的JSX侣诺,在FormattedDate函數(shù)里通過(guò)props.date獲取傳入的date
7殖演、這時(shí)候就已經(jīng)可以看到三個(gè)Clock顯示時(shí)間了
8、那時(shí)間怎么自動(dòng)更新的呢年鸳?當(dāng)Clock被插入DOM時(shí)趴久,會(huì)觸發(fā)componentDidMount,當(dāng)Clock從DOM移除時(shí)阻星,會(huì)觸發(fā)componentWillUnmount朋鞍,所以在componentDidMount調(diào)用時(shí)開(kāi)始定時(shí)更新,在componentWillUnmount關(guān)閉定時(shí)更新
9妥箕、定時(shí)更新會(huì)調(diào)用tick方法滥酥,tick方法調(diào)用setState來(lái)更新date字段
10、setState方法會(huì)觸發(fā)render方法的重新調(diào)用畦幢,進(jìn)而更新時(shí)間
由于筆者之前是做移動(dòng)端開(kāi)發(fā)坎吻,React的組件的概念跟iOS和Android的View的概念基本一致,甚至一些方法可以對(duì)應(yīng)的上宇葱,如componentDidMount和componentWillUnmount可對(duì)應(yīng)Android View中的onAttachedToWindow和onDetachedFromWindow, Clock中的render可對(duì)應(yīng)Android View中的onDraw瘦真。可以看出來(lái)編程理念都是大同小異黍瞧。組件化實(shí)際上就是模塊化诸尽,提高了代碼的復(fù)用性和可維護(hù)性。