美文网首页React
React基础篇之组件实例三大属性state

React基础篇之组件实例三大属性state

作者: 硅谷干货 | 来源:发表于2021-12-07 09:19 被阅读0次

概念

<script type="text/babel">
  //1.创建组件
  class Weather extends React.Component{
    
    //构造器调用几次? ———— 1次
    constructor(props){
      console.log('constructor');
      super(props)
      //初始化状态
      this.state = {isHot:false,wind:'微风'}
      //解决changeWeather中this指向问题
      this.changeWeather = this.changeWeather.bind(this)
    }

    //render调用几次? ———— 1+n次 1是初始化的那次 n是状态更新的次数
    render(){
      console.log('render');
      //读取状态
      const {isHot,wind} = this.state
      return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
    }

    //changeWeather调用几次? ———— 点几次调几次
    changeWeather(){
      //changeWeather放在哪里? ———— Weather的原型对象上,供实例使用
      //由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
      //类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
      
      console.log('changeWeather');
      //获取原来的isHot值
      const isHot = this.state.isHot
      //严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
      this.setState({isHot:!isHot})
      console.log(this);

      //严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
      //this.state.isHot = !isHot //这是错误的写法
    }
  }
  //2.渲染组件到页面
  ReactDOM.render(<Weather/>,document.getElementById('test'))
      
</script>

简写方式

<script type="text/babel">
  //1.创建组件
  class Weather extends React.Component{
    //初始化状态
    state = {isHot:false,wind:'微风'}

    render(){
      const {isHot,wind} = this.state
      return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
    }

    //自定义方法————要用赋值语句的形式+箭头函数
    changeWeather = ()=>{
      const isHot = this.state.isHot
      this.setState({isHot:!isHot})
    }
  }
  //2.渲染组件到页面
  ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
上一篇:React基础篇之自定义组件 - 简书 (jianshu.com)
下一篇:React基础篇之组件实例三大属性props - 简书 (jianshu.com)

点赞加关注,永远不迷路

相关文章

网友评论

    本文标题:React基础篇之组件实例三大属性state

    本文链接:https://www.haomeiwen.com/subject/rkpvxrtx.html