Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React.Component
is provided by React
.
Components主要是用React来开发相互独立UI控件的规范,或者说是模板也行,是React组件开发的使用最频繁的组件。
1. 一个简单的栗子🌰
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
2. 生命周期
1 组件加载
-
constructor()
构造方法,主要用来初始化类 -
componentWillMount()
加载前的处理 -
render()
渲染 -
componentDidMount()
加载完成后的处理
2 组件渲染
React中通过props和state来控制渲染的内容,所以以下方法中可以通过对props和state作监控或处理来影响渲染。
-
componentWillReceiveProps()
收到传进来props前 -
shouldComponentUpdate()
判断是否需要更新UI,只有返回true的时候才会刷新UI,默认也是true,可以根据实际情况做优化。 -
componentWillUpdate()
更新前的处理 -
render()
更新UI -
componentDidUpdate()
更新完成后
3 组件卸载
当组件需要对脱离后的组件做部分资源释放,需要考虑该部分
-
componentWillUnmount()
组件卸载前的处理
4 组件更新
-
setState()
设置state后会触发组件渲染的一系列检查来决定更要不要更新UI -
forceUpdate()
强制刷新UI
5 组件类属性
-
defaultProps
默认的props值 -
displayName
主要是调试时组件的显示名,自动设置
6 组件实例属性
网友评论