React中有兩種組件:函數(shù)組件(Functional Components) 和類組件(Class Components)。
來看一個(gè)函數(shù)組件的例子:
function Welcome = (props) => {
const sayHi = () => {
alert(Hi ${props.name});
}
return (
<div>
<h1>Hello, {props.name}</h1>
<button onClick ={sayHi}>Say Hi</button>
</div>
)
}
把上面的函數(shù)組件改寫成類組件:
import React from 'react'
class Welcome extends React.Component {
constructor(props) {
super(props);
this.sayHi = this.sayHi.bind(this);
}
sayHi() {
alert(Hi ${this.props.name});
}
render() {
return (
<div>
<h1>Hello, {this.props.name}</h1>
<button onClick ={this.sayHi}>Say Hi</button>
</div>
)
}
}
兩種實(shí)現(xiàn)的區(qū)別:
1、函數(shù)組件的代碼量比類組件要少一些,所以函數(shù)組件比類組件更加簡潔
2、最佳實(shí)踐且更容易理解。函數(shù)組件看似只是一個(gè)返回值是DOM結(jié)構(gòu)的函數(shù),它其實(shí)是無狀態(tài)組件(Stateless Components)的思想。函數(shù)組件中,無法使用State,也無法使用組件的生命周期方法,這就決定了函數(shù)組件都是展示性組件(Presentational Components),接收Props,渲染DOM,而不關(guān)注其他邏輯。
2、函數(shù)組件中沒有this。而在類組件中,你依然要記得綁定this這個(gè)瑣碎的事情。
3、性能。目前React會(huì)把函數(shù)組件在內(nèi)部轉(zhuǎn)換成類組件,所以使用函數(shù)組件和使用類組件在性能上并無大的差異。但是,React官方已承諾,未來將會(huì)優(yōu)化函數(shù)組件的性能,因?yàn)楹瘮?shù)組件不需要考慮組件狀態(tài)和組件生命周期方法中的各種比較校驗(yàn),所以有很大的性能提升空間。
所以,當(dāng)我們動(dòng)手寫組件時(shí),應(yīng)該盡可能多地使用函數(shù)組件。