React Component Specs and Lifecycle (組件和生命週期)

組件規格

當建立一個React組件,並調用 React.createClass(),你須要提供一些Object對象,例如必須的render,還有其餘一些可選的Object對象。javascript

render

這個函數對象必須存在,且必定存在返回值。java

render: function () {
      return (<h2>Hello, World!</h2>);
}

官方規範說明這個方法必定要pure(乾淨),保證職責單一,全部數據經過propsstate來。利於組件的複用和維護。寫React必定要約束好各類規範!
返回值是 ReactElement函數

getInitialState

object getInitialState()

在組件裝載前會調用一次,函數的返回值對象,能夠在this.state查詢和使用。this

getDefaultProps

object getDefaultProps()

在組件裝載前會調用一次,函數的返回值對象,能夠在this.props查詢和使用。
和state不一樣的是,props在每一個實例裏均可以訪問到,只會拷貝一次,而this.state是實例獨享的。spa

propTypes

object propTypes

能夠約束檢測你的參數的,發現不匹配就會console.wran()來提示錯誤,可是不會報錯不執行。debug

mixins(ES6已經不支持了)

array mixins

支持多個組件之間共享公用的方法,共享使用共同的變量和方法。code

statics

object statics

給你的組件增長靜態的方法。component

var MyComponent = React.createClass({
  statics: {
    customMethod: function(foo) {
      return foo === 'bar';
    }
  },
  render: function() {
  }
});

MyComponent.customMethod('bar');  // true

 

displayName

string displayName

用於debug時候的定位。對象

生命週期方法

實例化

當首次使用組件類時,下面這些方法依次被調用。blog

  • getDefaultProps

  • getInitialState

  • componentWillMount

  • render

  • componentDidMount

當組件類再次被調用時getDefaultProps方法不會被調用。

存在期

當實例已經生成,修改屬性時,如下方法會依次被調用

  • componentWillReceiveProps

  • shouldComponentUpdate

  • componentWillUpdate

  • render

  • componentDidUpdate

相關文章
相關標籤/搜索