二、react组件及生命周期

1、组件

一般来说,一个组件类由 extends Component 创建,并且提供一个 render方法以及其他可选的生命周期函数、组件相关的事件或方法来定义
注意: 在 JavaScript class 中,每次你定义其子类的构造函数时,都需要调用 super 方法。因此,在所有含有构造函数的的 React 组件中,构造函数必须以 super(props) 开头。

import React, { Component } from 'react';
import { render } from 'react-dom';

class LikeButton extends Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  handleClick(e) {
    this.setState({ liked: !this.state.liked });
  }

  render() {
    const text = this.state.liked ? 'like' : 'haven\'t liked';
    return (
      

You {text} this. Click to toggle.

); } } render( , document.getElementById('example') );

注:1)组件的return函数返回的HTML节点必须是一个
2)绑定事件使用驼峰式命名如"onClick"
3)要显示调用bind(this)将事件函数上下文绑定在组件实例上
4)可以给外部使用的组件定义:

export default class ComponentHeader extends Component{}

5)入口的定义:

render(
    ,
    document.getElementById('example')
);

2、生命周期

1)getInitialState初始化this.state的值,只在组件装载之前调用一次。
ES6 去掉了getInitialState函数,使用 ES6 的语法,你也可以在构造函数中初始化状态,如:

class Counter extends Component {
  constructor(props) {
    super(props); //super指的是父类构造函数
    this.state = { count: props.initialCount };
  }

  render() {
    // ...
  }
}

2)getDefaultProps 只在组件创建时调用一次并缓存返回的对象(即在React.createClass之后就会调用)。在这个方法里面不能依赖 this 获取到这个组件的实例。
ES6 去掉了getDefaultProps,es6定义默认props的正确方式:

class MyDemo extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return 

This is my {this.props.name}

} } //由于是用ES6 class语法创建组件,其内部只允许定义方法,而不能定义属性,class的属性只能定义在class之外。所以defaultProps要写在组件外部。 MyDemo.defaultProps = { name: 'demo' };

3)render
必须
组装生成这个组件的 HTML 结构(使用原生 HTML 标签或者子组件),也可以返回 null或者 false,这时候 ReactDOM.findDOMNode(this)会返回 null

3、生命周期函数

1)装载组件触发
componentWillMount
只会在装载之前调用一次,在 render之前调用,你可以在这个方法里面调用 setState改变状态,并且不会导致额外调用一次render
componentDidMount
只会在装载完成之后调用一次,在render之后调用,从这里开始可以通过ReactDOM.findDOMNode(this) 获取到组件的 DOM 节点。

2)更新组件触发
这些方法不会在首次render 组件的周期调用

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • componentDidUpdate

3)卸载组件触发

  • componentWillUnmount

你可能感兴趣的:(二、react组件及生命周期)