React

深入React组件的数据:prop、state

2018-08-28  本文已影响47人  Lia代码猪崽

一、prop

React中,prop(propety的简写)是从外部传递给组件的数据,一个组件通过定义自己能够接受的prop就定义了自己对外公共接口。

1.给prop赋值
// 一段JSX代码中:
<SampleButton id="sample" borderWidth={2} onClick={onButtonClick} style={{ color: "red" }} />
2.读取prop的值
class Counter extends Component {
  constructor(props) {
    super(props)

    this.onClickIncrementButton = this.onClickIncrementButton.bind(this)
    this.onClickDecrementButton = this.onClickDecrementButton.bind(this)

    this.state = {
      count: props.initValue || 0    
    }
  }
}
3.propTypes检查

ES6方法定义的组件类中,可以通过增加类的propTypes属性来定义prop的规格,这不只是声明,还是一种限制。在运行时和静态代码检查时,都可以根据propTypes 判断外部世界是否正确地使用了组件。

Counter.propTypes = {
  caption: PropTypes.string.isRequiered,
  initValue: PropTypes.number
}

propTypes虽然能够在开发阶段发现代码中的问题,但是放在产品环境不合适,会占用一些代码空间,消耗CPU计算资源。所以在开发阶段使用,当部署到环境产品时应该去掉。
babel-react-optimize就有这个功能,通过npm来安装,但是应该确保只在发布产品代码时使用它。

二、state

state表示组件的内部状态。由于React组件不能修改传入的prop,所以需要记录自身数据变化,就要用到state

1.初始化state

通常都会在组件类的构造函数的结尾处初始化state

constructor(props) {
  ...
  this.state = {
    count: props.initValue || 0
  }
}

可以用ReactdefaultProps

Counter.defaultProps = {
  initValue: 0
}

这样,Counter构造函数中的this.state初始化中可以省去判断条件,代码可以简化为:

constructor(props) {
 ...
 this.state = {
   count: props.initValue
 }
}

如果实例中即使没有指定count属性的initValue,实例组件中的count属性也能收到一个默认的属性值0。

2.读取和更新state

通过给buttononClick属性挂载点击事件处理函数,我们可以改变组件的state,以点击按钮给count加1的响应事件为例:

onClickIncrementButton() {
  this.setState({ count: this.state.count + 1 })
}
上一篇下一篇

猜你喜欢

热点阅读