React 三大组件核心属性之 state

  • state 是组件对象最重要的属性,知识对象(可以包含多个 key-value 的组合)
  • 组件被称为“状态机”,通过更新组件的state来更新对应的页面显示(重新渲染组件)

模拟需求

  • 点击文字,轮番显示今天天气很炎热和今天天气很凉爽

示例 一般写法

class Weather extends React.Component {
    // 构造器调用 1 次
	constructor(props) { 
	    super();
		this.state = {isHot: false};
        // 解决 changeWeather 中的 this 指向问题,将原型上的方法挂载到了实例上
		this.changeWeather = this.changeWeather.bind(this);
	}

   /*   render方法调用 n+1 次
    *   1 是初始化那次
    *   n 是装填更新的次数
    */
	render() {
        // onClick={this.changeWeather} 注册事件
		return <h2 onClick={this.changeWeather}>今天天气很{this.state.isHot ? '炎热' : '凉爽'}</h2>;
	}

     /* changeWeather方法调用 n 次
    *   n 是装填更新的次数
    */
	changeWeather() {
        // changeWeather 放在了 Weather 的原型对象上,供实例使用
        // 由于 changeWeather 是作为 onCLick 的回调,所以不是通过实例调用的,是直接调用
        // 类中的方法默认开启了局部的严格模式,所以 changeWeather 中的 this 为 undefined
        // 注意:状态更新必须通过 setState 进行更新, 且更新是一种合并,不是替换
		this.setState({isHot: !this.state.isHot})
        // 注意:状态(state)不可以直接更改
        //this.state.isHot = !this.state.isHot  错误写法
	}
}

示例 简洁写法

  • 类中不用接收参数的"死数据"可以不写在 constructor 构造器中
  • 可以用箭头函数改变 this 指向
class Weather extends React.Component {
    state = {isHot: false};

	render() {
        // onClick={this.changeWeather} 注册事件
		return <h2 onClick={this.changeWeather}>今天天气很{this.state.isHot ? '炎热' : '凉爽'}</h2>;
	}

	changeWeather: () => {
		this.setState({isHot: !this.state.isHot})
	}
}
posted @   懒惰ing  阅读(94)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-03-17 小程序的配置文件
2020-03-17 markdown 常见用法
2020-03-17 小程序开发前准备
点击右上角即可分享
微信分享提示