React学习(从零基础到精通)0110

本文解析了React组件的三个关键属性:state用于存储组件内部状态,props用于父组件向子组件传递数据,refs用于访问组件实例。实例演示了如何正确管理state的更新和避免直接修改,以及props和refs的使用场景。
摘要由CSDN通过智能技术生成

组件实例三大属性 state,props,refs

state

    <script type="text/babel">
    //创建类式组件
    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} = this.state;
            return <h1 id="title" onClick={this.changeWeather}>今天天气很{isHot ? "炎热" : "凉爽"}</h1>
        }
        //changeWeather调用几次? --- 点几次调用几次
        changeWeather(){
            console.log("changeWeather")
            //changeWeather放在哪里? --- Weather的原型对象上,供实例使用
            //通过Weather实例调用changeWeather时,changeWeather中的this就是Weather实例

            //由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用。
            //类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
            console.log(this.state.isHot);
            
            //获取原来的isHot值
            const isHot = this.state.isHot;
            //严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
            //this.state.isHot = !isHot//这是错误的写法
            //严重注意:状态(state)必须通过setState进行修改
            this.setState({isHot:!isHot})

        }
    }
    ReactDOM.render(<Weather/>,document.getElementById("test"))
    const title = document.getElementById("title");
    </script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值