react学习-6.React组件的生命周期

1.组件的生命周期

一个组件完整的生命周期包含实例化阶段、活动阶段、销毁阶段三个阶段。每个阶段又由相应的方法管理。

过程中涉及三个主要的动作术语:

  • mounting:表示正在挂接虚拟DOM到真实DOM。
  • updating:表示正在被重新渲染。
  • unmounting:表示正在将虚拟DOM移除真实DOM。(只有一个,因为组件卸载完成后已经不存在了,所以监控不到。)

每个动作术语提供两个函数:

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate()
  • componentDidUpdate()
  • componentWillUnmount()

具体什么意思直接看demo。

class SwitchInput extends React.Component {
  constructor(props) {
    super(props)
    console.log('1.getInitialSate:初始化数据:');
    
    this.state = {
      enable: true
    }
   
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(event) {
    this.setState({
      enable: !this.state.enable
    })
  }
  componentWillMount(){
    console.log('2.componentWillMount:组件正在渲染,将要挂载到dom中');
   }
   componentDidMount(){
       console.log('3.componentDidMount:组件渲染完毕,真实的DOM已经渲染出来');
   }
   componentWillUpdate(){
       console.log('4.componentWillUpdate:接收到新的props或者state后,进行渲染之前调用');
   }
   componentDidUpdate(){
       console.log('5.componentDidUpdate:完成新的渲染');
   }

  render() {
      return (
       <p>
         <input type="text" disabled={this.state.enable}/>
         <button onClick={this.handleClick}>
              改变输入框编辑状态
         </button>
         自定义属性:{this.props.myattr}
       </p>
      )
  }
}
SwitchInput.defaultProps={
  myattr: "我是默认的属性" 
} 
ReactDOM.render(<SwitchInput/>, document.getElementById('root'));

结果先显示1,2,3,点击按钮显示4,5。

2.组件的生命周期练习

这个案例是自定义一个组件,并把组件进行不断闪烁,形成一种动画形式。

image
class SwitchOpacity extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      opacity: 1
    }
  }

  componentDidMount() {
    setInterval(()=>{
      var num=this.state.opacity-0.2
      if(num<=0){
        num=1
      }
      this.setState({
        opacity:num
      })
    },300)
  }
 
  render() {
      return (
       <p style={{opacity:this.state.opacity}}>
        闪动的文字
       </p>
      )
  }
}

ReactDOM.render(<SwitchOpacity/>, document.getElementById('root'));
  • 组件渲染完毕后进行更改透明度
  • 对标签添加样式时,用两个大括号,最外面的就是之前将的jsx语法,表达式。里面的表示一个js对象。所以是两个大括号。

下一篇——react学习-7.React事件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容