热门搜索 :
考研考公
您的当前位置:首页正文

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

来源:东饰资讯网

1.组件的生命周期

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

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

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

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

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

具体什么意思直接看demo。

class SwitchInput extends  {
  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(){
    
   }
   componentDidMount(){
       
   }
   componentWillUpdate(){
       
   }
   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  {
  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对象。所以是两个大括号。
Top