美文网首页
reactnative学习-组建(Component)

reactnative学习-组建(Component)

作者: 码字农民工 | 来源:发表于2018-04-30 20:23 被阅读34次

概述

Components(组件)为reactnative不可缺少的一部分,官方为我们定义好了很多组件,例如View,Text,Image等等,同样我们可以自己定义组件,去满足业务不同的需求,以及整个项目的复用性以及可扩展性。今天我们就来讲讲组件。

生命周期

我们先来上一张经典的图来看看。


component.png

由上图我们可以看出来整个component从装载到卸载的过程,我们来一张表来说明一下。

方法名 作用 说明
constructor 构造函数,初始化需要的state 我们可以在此方法里面初始化state(component需要的数据与状态)
componentWillMount 控件渲染前触发 对state进行最后的修改
rander 渲染控件的方法
componentDidMount 控件渲染后触发 进行网络/耗时操作
componentWillReceiveProps 组件接收到新的props时被调用
shouldComponentUpdate 当组件接收到新的props和state时调用 我们可以在此方法里面进行nextProps/nextState与props/state的数据对比,如果数据相同,我们可以返回false来禁止rander刷新组件。
componentWillUpdate props或者state改变,并且此前的shouldComponentUpdate方法返回为 true会调用该方法
componentDidUpdate 组件重新渲染完成后会调用此方法
componentWillUnmount 组件卸载和销毁之前被调用 我们可以在此方法里面关闭一些耗时操作,避免不必要的内存开销

实例属性

props

this.props包含由此组件的调用者定义的props。通俗点来讲就是调用此Component组件的地方传过来的属性。我们在本Component中不应该去改变props里面的值,而是调用者通过改变props的值来引起该组件的变化。

state

state包含特定于此组件的数据,可能随时间更改。通俗点来讲就是此Component里面定义的一些数据。我们这里需要注意永远不要直接改变this.state,因为调用setState()之后可以替换你所做的各种变化, 通常应该把this.state看作是不可变的。

类的属性

propTypes

propTypes也是类组件本身上的一个属性,用来规范props应该是什么类型。 它是从props的名称到React.PropTypes中定义的类型的映射。 在开发模式下,当为prop设置一个不是指定格式的无效值时,会在JavaScript控制台中显示警告信息。 在生产模式下,为了提高效率,不会进行propTypes检查。例如:

//写法一
CustomButton.propTypes = {
  color: React.PropTypes.string
};
class CustomButton extends React.Component {
   // ...
   //写法二
   CustomButton.propTypes = {
    color: React.PropTypes.string
   };
}

defaultProps

defaultProps是类组件本身的属性,用来设置类组件的默认props。 可以用来给未传入值的props设置默认值。例如:

//写法一
CustomButton.defaultProps = {
    color: 'blue';
}
class CustomButton extends React.Component {
    // ...
    //写法二
    static defaultProps = {
      color: 'blue';
    }
}

相关文章

网友评论

      本文标题:reactnative学习-组建(Component)

      本文链接:https://www.haomeiwen.com/subject/znhtrftx.html