React当前已经更新到了16版本,以下内容基于该版本进行解析。
概览
React 的组件可以定义为 class 或函数的形式。class 组件目前提供了更多的功能,这些功能将在此章节中详细介绍。如需定义 class 组件,需要继承 React.Component
:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
在 React.Component
的子类中有个必须定义的 render()
函数。介绍其他方法均为可选。
组件的生命周期
每个组件都包含“生命周期方法”,你可以重写这些方法,以便于在运行过程中特定的阶段执行这些方法。在下述列表中,常用的生命周期方法会被加粗。其余生命周期函数的使用则相对罕见。
下图为常见生命周期的图谱:
挂载
当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
注意:之前componentWillMount()将会被移除,在所有新组件都不应该使用该函数,该生命周期的部分功能实现根据需要可以在constructor或componentDidMount中实现
更新
当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
注意:之前有两个方法在未来版本将会移除:componentWillUpdate()和componentReceivProps()
卸载
当组件从 DOM 中移除时会调用如下方法:
componentWillUnmount()