前言
當(dāng)我們談起React的時(shí)候,多半會將注意力集中在組件之上,思考如何將頁面劃分成一個(gè)個(gè)組件,以及如何編寫可復(fù)用的組件。但對于接觸React不久,還沒有真正用它做一個(gè)完整項(xiàng)目的人來說,理解如何創(chuàng)建一個(gè)組件也并不那么簡單。
在最開始的時(shí)候我以為創(chuàng)建組件只需要調(diào)用createClass這個(gè)api就可以了;但學(xué)習(xí)了ES6的語法后,又知道了可以利用繼承,通過extends React.component來創(chuàng)建組件;后來在閱讀別人代碼的時(shí)候又發(fā)現(xiàn)了PureComponent以及完全沒有繼承,僅僅通過返回JSX語句的方式創(chuàng)建組件的方式。
下面這篇文章,就將逐一介紹這幾種創(chuàng)建組件的方法,分析其特點(diǎn),以及如何選擇使用哪一種方式創(chuàng)建組件。
幾種方法
1.createClass
如果你還沒有使用ES6語法,那么定義組件,只能使用React.createClass這個(gè)helper來創(chuàng)建組件,下面是一段示例:
var React = require("react"); var Greeting = React.createClass({ propTypes: { name: React.PropTypes.string //屬性校驗(yàn) }, getDefaultProps: function() { return { name: 'Mary' //默認(rèn)屬性值 }; }, getInitialState: function() { return {count: this.props.initialCount}; //初始化state }, handleClick: function() { //用戶點(diǎn)擊事件的處理函數(shù) }, render: function() { return <h1>Hello, {this.props.name}</h1>; } }); module.exports = Greeting;
這段代碼,包含了組件的幾個(gè)關(guān)鍵組成部分,這種方式下,組件的props、state等都是以對象屬性的方式組合在一起,其中默認(rèn)屬props和初始state都是返回對象的函數(shù),propTypes則是個(gè)對象。這里還有一個(gè)值得注意的事情是,在createClass中,React對屬性中的所有函數(shù)都進(jìn)行了this綁定,也就是如上面的hanleClick其實(shí)相當(dāng)于handleClick.bind(this) 。
2.component
因?yàn)镋S6對類和繼承有語法級別的支持,所以用ES6創(chuàng)建組件的方式更加優(yōu)雅,下面是示例:
import React from 'react'; class Greeting extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; this.handleClick = this.handleClick.bind(this); } //static defaultProps = { // name: 'Mary' //定義defaultprops的另一種方式 //} //static propTypes = { //name: React.PropTypes.string //} handleClick() { //點(diǎn)擊事件的處理函數(shù) } render() { return <h1>Hello, {this.props.name}</h1>; } } Greeting.propTypes = { name: React.PropTypes.string }; Greeting.defaultProps = { name: 'Mary' }; export default Greating;
可以看到Greeting繼承自React.component,在構(gòu)造函數(shù)中,通過super()來調(diào)用父類的構(gòu)造函數(shù),同時(shí)我們看到組件的state是通過在構(gòu)造函數(shù)中對this.state進(jìn)行賦值實(shí)現(xiàn),而組件的props是在類Greeting上創(chuàng)建的屬性,如果你對類的屬性和對象的屬性的區(qū)別有所了解的話,大概能理解為什么會這么做。
對于組件來說,組件的props是父組件通過調(diào)用子組件向子組件傳遞的,子組件內(nèi)部不應(yīng)該對props進(jìn)行修改,它更像是所有子組件實(shí)例共享的狀態(tài),不會因?yàn)樽咏M件內(nèi)部操作而改變,因此將props定義為類Greeting的屬性更為合理,而在面向?qū)ο蟮恼Z法中類的屬性通常被稱作靜態(tài)(static)屬性,這也是為什么props還可以像上面注釋掉的方式來定義。
對于Greeting類的一個(gè)實(shí)例對象的state,它是組件對象內(nèi)部維持的狀態(tài),通過用戶操作會修改這些狀態(tài),每個(gè)實(shí)例的state也可能不同,彼此間不互相影響,因此通過this.state來設(shè)置。
用這種方式創(chuàng)建組件時(shí),React并沒有對內(nèi)部的函數(shù),進(jìn)行this綁定,所以如果你想讓函數(shù)在回調(diào)中保持正確的this,就要手動對需要的函數(shù)進(jìn)行this綁定,如上面的handleClick,在構(gòu)造函數(shù)中對this 進(jìn)行了綁定。
3.PureComponet
我們知道,當(dāng)組件的props或者state發(fā)生變化的時(shí)候:React會對組件當(dāng)前的Props和State分別與nextProps和nextState進(jìn)行比較,當(dāng)發(fā)現(xiàn)變化時(shí),就會對當(dāng)前組件以及子組件進(jìn)行重新渲染,否則就不渲染。有時(shí)候?yàn)榱吮苊饨M件進(jìn)行不必要的重新渲染,我們通過定義shouldComponentUpdate來優(yōu)化性能。例如如下代碼:
class CounterButton extends React.Component { constructor(props) { super(props); this.state = {count: 1}; } shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; } return false; } render() { return ( <button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button> ); } }
shouldComponentUpdate通過判斷props.color和state.count是否發(fā)生變化來決定需不需要重新渲染組件,當(dāng)然有時(shí)候這種簡單的判斷,顯得有些多余和樣板化,于是React就提供了PureComponent來自動幫我們做這件事,這樣就不需要手動來寫shouldComponentUpdate了:
class CounterButton extends React.PureComponent { constructor(props) { super(props); this.state = {count: 1}; } render() { return ( <button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button> ); } }
大多數(shù)情況下, 我們使用PureComponent能夠簡化我們的代碼,并且提高性能,但是PureComponent的自動為我們添加的shouldComponentUpate函數(shù),只是對props和state進(jìn)行淺比較(shadow comparison),當(dāng)props或者state本身是嵌套對象或數(shù)組等時(shí),淺比較并不能得到預(yù)期的結(jié)果,這會導(dǎo)致實(shí)際的props和state發(fā)生了變化,但組件卻沒有更新的問題。
例如下面代碼有一個(gè)ListOfWords組件來將單詞數(shù)組拼接成逗號分隔的句子,它有一個(gè)父組件WordAdder讓你點(diǎn)擊按鈕為單詞數(shù)組添加單詞,但他并不能正常工作:
class ListOfWords extends React.PureComponent { render() { return <div>{this.props.words.join(',')}</div>; } } class WordAdder extends React.Component { constructor(props) { super(props); this.state = { words: ['marklar'] }; this.handleClick = this.handleClick.bind(this); } handleClick() { // 這個(gè)地方導(dǎo)致了bug const words = this.state.words; words.push('marklar'); this.setState({words: words}); } render() { return ( <div> <button onClick={this.handleClick} /> <ListOfWords words={this.state.words} /> </div> ); } }
這種情況下,PureComponent只會對this.props.words進(jìn)行一次淺比較,雖然數(shù)組里面新增了元素,但是this.props.words與nextProps.words指向的仍是同一個(gè)數(shù)組,因此this.props.words !== nextProps.words 返回的便是flase,從而導(dǎo)致ListOfWords組件沒有重新渲染,筆者之前就因?yàn)閷Υ瞬惶私猓S意使用PureComponent,導(dǎo)致state發(fā)生變化,而視圖就是不更新,調(diào)了好久找不到原因~。
最簡單避免上述情況的方式,就是避免使用可變對象作為props和state,取而代之的是每次返回一個(gè)全新的對象,如下通過concat來返回新的數(shù)組:
handleClick() { this.setState(prevState => ({ words: prevState.words.concat(['marklar']) })); }
你可以考慮使用Immutable.js來創(chuàng)建不可變對象,通過它來簡化對象比較,提高性能。
這里還要提到的一點(diǎn)是雖然這里雖然使用了Pure這個(gè)詞,但是PureComponent并不是純的,因?yàn)閷τ诩兊暮瘮?shù)或組件應(yīng)該是沒有內(nèi)部狀態(tài)。
4.Stateless Functional Component
上面我們提到的創(chuàng)建組件的方式,都是用來創(chuàng)建包含狀態(tài)和用戶交互的復(fù)雜組件,當(dāng)組件本身只是用來展示,所有數(shù)據(jù)都是通過props傳入的時(shí)候,我們便可以使用Stateless Functional Component來快速創(chuàng)建組件。例如下面代碼所示:
import React from 'react'; const Button = ({ day, increment }) => { return ( <div> <button onClick={increment}>Today is {day}</button> </div> ) } Button.propTypes = { day: PropTypes.string.isRequired, increment: PropTypes.func.isRequired, }
這種組件,沒有自身的狀態(tài),相同的props輸入,必然會獲得完全相同的組件展示。因?yàn)椴恍枰P(guān)心組件的一些生命周期函數(shù)和渲染的鉤子,所以不用繼承自Component顯得更簡潔。
對比
createClass vs Component
對于React.createClass 和 extends React.Component本質(zhì)上都是用來創(chuàng)建組件,他們之間并沒有絕對的好壞之分,只不過一個(gè)是ES5的語法,一個(gè)是ES6的語法支持,只不過createClass支持定義PureRenderMixin,這種寫法官方已經(jīng)不再推薦,而是建議使用PureComponent。
pureComponent vs Component
通過上面對PureComponent和Component的介紹,你應(yīng)該已經(jīng)了解了二者的區(qū)別:PureComponent已經(jīng)定義好了shouldUpdateComponent而Component需要顯示定義。
Component vs Stateless Functional component
Component包含內(nèi)部state,而Stateless Functional Component所有數(shù)據(jù)都來自props,沒有內(nèi)部state;
1.Component 包含的一些生命周期函數(shù),Stateless Functional Component都沒有,因?yàn)镾tateless Functional
2.component沒有shouldComponentUpdate,所以也無法控制組件的渲染,也即是說只要是收到新的props,Stateless Functional Component就會重新渲染。
3.Stateless Functional Component 不支持Refs
選哪個(gè)?
這里僅列出一些參考:
1.createClass, 除非你確實(shí)對ES6的語法一竅不通,不然的話就不要再使用這種方式定義組件。
2.Stateless Functional Component, 對于不需要內(nèi)部狀態(tài),且用不到生命周期函數(shù)的組件,我們可以使用這種方式定義組件,比如展示性的列表組件,可以將列表項(xiàng)定義為Stateless Functional Component。
3.PureComponent/Component,對于擁有內(nèi)部state,使用生命周期的函數(shù)的組件,我們可以使用二者之一,但是大部分情況下,我更推薦使用PureComponent,因?yàn)樗峁┝烁玫男阅埽瑫r(shí)強(qiáng)制你使用不可變的對象,保持良好的編程習(xí)慣。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com