React中有兩種組件:函數組件(Functional Components) 和類組件(Class Components)。據我觀察,大部分同窗都習慣於用類組件,而不多會主動寫函數組件,包括我本身也是這樣。但實際上,在使用場景和功能實現上,這兩類組件是有很大區別的。前端
來看一個函數組件的例子:react
function Welcome = (props) => { const sayHi = () => { alert(`Hi ${props.name}`); } return ( <div> <h1>Hello, {props.name}</h1> <button onClick ={sayHi}>Say Hi</button> </div> ) }
把上面的函數組件改寫成類組件:程序員
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> ) } }
下面讓咱們來分析一下兩種實現的區別:數組
this
。因此你不再須要考慮this
帶來的煩惱。而在類組件中,你依然要記得綁定this
這個瑣碎的事情。如示例中的sayHi
。因此,當你下次在動手寫組件時,必定不要忽略了函數組件,應該儘量多地使用函數組件。less
歡迎關注個人公衆號:老幹部的大前端,領取21本大前端精選書籍!函數