LoginSignup
0
1

More than 5 years have passed since last update.

React组件定义和生命周期

Last updated at Posted at 2016-09-05

React其实从目前的了解来看,我理解的它核心的东西就是一个虚拟 DOM 的概念, 通过修改虚拟 DOM 来刷新用户最终看到的 UI.

组件定义

通过React.createClass()我们就可以得到react 它的核心 -- 组件. 而对于这个组件, 它在 react 里如何定义, 以及它的生命周期. 下面我们展开讨论.

调用createClass()方法,需要传递一个对象, 这个对象必须包含一个render() 方法, 还有一切其他的生命周期方法.

其实一个所谓`组件`,它就是一个`对象`, javascript 世界里的`对象`, 也就是我们常见的 hash.<sup>[1]</sup> 它必须包含一个` render` 方法, 同时可以有其他可选的生命周期方法. 

[1], 其实这样的表示有些误差, 目前我们可以通过 es5,或者 es2015(es6)不同的语法来写这个 class, 但是终归它在跑之前还是要编译到 es5的语法里, 也就是各种 hash 的集合罢了.

render

ReactElement render()

这是一个必选的方法. 当它被调用的时候, 它会验证this.propsthis.state, 然后最终返回一个单一子元素. 这个子元素可以是原生 DOM 的虚拟展现形式(如

或者 React.DOM.div()), 也可以是我们自定义的复合的元素组件.

也可以返回一个 null 或者 false 来表明什么都不用渲染. 其实对于 React 它背后做的就是渲染一个<noscript>tag 来完成当前我们差分的逻辑. 当返回 null 或者 false 的时候 ReactDOM.findDOMNode(this)就会返回null.

这个render()函数必须是pure 什么意思呢, 不会去修改组件的状态,每次都应该返回同样的结果. 而且它不能够读取或者修改 DOM, 除非和当前浏览器发生交互. (如使用 setTimeout())当如果有这样的需求时最好使用componentDidMount()这样的方法或者生命周期里的其他方法,尽量保持render() 这个方法的纯洁性,

getInitialState

object getInitialState()

在组件挂载之前被调用.主要是初始化this.state.

getDefaultProps

object getDefaultProps()

只调用一些用来创建实例化这个类, 接着就会缓存起来这个. 所有属性都被 map 到this.props. 这个方法在创建实例之前调用, 然后所有实例共享当前的属性.

propTypes

object propTypes

这个对象允许我们能够验证组件的属性在赋值给组件前

mixins

array mixins

这个数据包含一些共享的方法可以用来在多组件间重用

statics

object statics

这个使用声明一些静态函数的. 这样就能够直接在组件类上使用.

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

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

displayName

string displayName

在 debug 的时候使用这个字符串. JSX 会自动 set 这个值.

生命周期方法

看看他具体生命周期方法:

挂载 componentWillMount

void componentWillMount()

挂在完成 componentDidMount

void componentDidMount()

更新 componentWillReceiveProps

void componentWillReceiveProps

更新 shouldComponentUpdate

boolean shouldComponentUpdate()

更新 componentWillUpdate

void componentWillUpdate()

更新 componentDidUpdate

void componentDidUpdate()

卸载 componentWillUnmount

void componentWillUnmount()

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1