React+AntDesign入门:一、React生命周期实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29668759/article/details/88576172

一、React生命周期

  • getDefaultProps:初始化Props属性,Props来自于父组件或者其他组件传递过来的。
  • getInitialState:初始化我们当前组件的状态。
  • componentWillMount:组件在初始化之前会调用这个方法。
  • render:渲染UI。
  • componentDidMount:组件渲染完成之后会调用这个方法。
  • componentWillReceiveProps:父组件的传递东西过来时会调用这个方法。
  • shouldComponentUpdate:组件更新时调用。
  • componnetWillUpdate:组件更新前调用。
  • componentDidUppdate:组件更新后调用。
  • componentWillUnmount:组件销毁时调用

1.父组件Life.js

父组件为Life.js,里面有两个按钮,作用为把当前组件的count属性+1

import React from 'react';
import ChildLife from './ChildLife';

/**
 * 父组件
 */
class Life extends React.Component {

  //构造器
  constructor(props){
    super(props);

    this.state = {   //组件内的变量等都通过state来存取
      count : 0
    };
  }

  /**
   * 点击事件的第一种实现方式:
   */
  addCount = ()=>{
    this.setState({
      count : this.state.count + 1
    })
  }

  /**
   * 点击事件的第二种实现方式:
   */
  addCountBindThis(){
    this.setState({
      count : this.state.count + 1
    })
  }

  render() {
    return (
      <div>
        <p>看一下React生命周期</p>
        <button onClick={this.addCount}>按钮1:不使用bind</button>
        <button onClick={this.addCountBindThis.bind(this)}>按钮2:使用bind</button>
        <p>{this.state.count}</p>
        <ChildLife parentCount = {this.state.count}></ChildLife>
      </div>
    )

  }
}
export default Life;

2.子组件ChildLife.js

父组件传递父组件的count给子组件,名称为parentCount,子组件进行展示。

import React from 'react';

/**
 * 子组件
 */
class ChildLife extends React.Component{

  constructor(props){
    super(props);
    this.state={
      count : 0
    };
  }

  /** 生命周期们 **/

  componentWillMount() {  //组件在初始化之前会调用这个方法
    console.log("componentWillMount()  ->  组件在初始化之前会调用这个方法");
  }

  componentDidMount() { //组件渲染完成之后会调用这个方法
    console.log("componentDidMount()  ->  组件渲染完成之后会调用这个方法");
  }

  componentWillReceiveProps(newProps) { //父组件的传递东西过来时会调用这个方法
    console.log("componentWillReceiveProps()  ->  父组件的传递东西过来时会调用这个方法");
    console.log(newProps.parentCount)
  }



  render() {
    return(
      <div>
        <p>子组件:</p>
        <p>{this.props.parentCount}</p>
      </div>
    )
  }

}

export default ChildLife;

3.配置下路由让我们能够测试

项目是基于ant design pro2,修改config/router.config.js在这里插入图片描述

4.测试

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_29668759/article/details/88576172