例子
使用类组件
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>
)
}
}
将它改成函数组件
function Welcome = (props) => {
const sayHi = () => {
alert(`Hi ${props.name}`);
}
return (
<div>
<h1>Hello, {props.name}</h1>
<button onClick ={sayHi}>Say Hi</button>
</div>
)
}
与类组件的区别
- 没有this
- 无法被实例化
- 没有状态(state),所以函数组件也叫无状态组件(Stateless Components)
- 没有生命周期
所以函数特别适合用来写只接收props渲染DOM,不考虑其他逻辑的展示型组件(Presentational Components)