react基础内容

89 阅读1分钟

生命周期

  1. constructor 构造函数
  2. componentWillMount/UNSAFE_componentWillMount 组件将要渲染(17版本即将移除);
  3. componentDidMount 组件已经渲染完成,可在此获取dom操作。
  4. componentWillReceiveProps/UNSAFE_componentWillReceiveProps 将要接收新的props (17版本即将移除);
  5. shouldComponentUpdate 是否更新组件,可在此控制组件更新,常用在阻止重复渲染;
  6. componentWillUpdate/UNSAFE_componentWillUpdate 将要渲染组件 (17版本即将移除);
  7. getSnapshotBeforeUpdate 在最近的更改被提交到DOM元素前,使得组件可以在更改之前获得当前值,此生命周期返回的任意值都会传给componentDidUpdate;
  8. componentDidUpdate 组件更新完成;

常用静态函数

  1. getDerivedStateFromProps 在每次render之前调用,返回的值将放到state中。用来替代 componentWillReceiveProps
  2. defalutprops 组件默认props
  3. propTypes 定义组件props 类型

上下文传值

方式一: 16新特性 context

方式二:

//父组件
static childContextTypes = {
  type: PropTypes.string
}

getChildContext() {
    return {type: this.state.type};
}
  
//子组件
static contextTypes={
  type: PropTypes.string
}