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本大前端精选书籍!函数