React三大属性之一——state 属性
组件实例三大核心属性1:state
1.定义
1. state 是组件对象最重要的属性,值是对象(可以包含多个key-value)
2. 组件被称为"状态机",通过更新组件的 state 来更新对应的页面显示(重新渲染组件)
2. 注意
1. 组件中 render 方法中的 this 为组件实例对象
2. 组件自定义的方法中 this 为 undefined,如何解决?
1. 强制绑定 this:通过函数对象的 bind()
2. 箭头函数
3. 状态数据,不能直接修改或更新:使用React.component上的 setState() 方法对数据进行更新
<div id="test"></div>
<!-- 引入react核心库 -->
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<!-- 引入react-dom,用于支持react操作DOM -->
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- 引入babel,用于将jsx转为js -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type='text/babel'>
// 1.创建组件
class Weather extends React.Component {
// 构造器调用几次?——1次
constructor(props) {
super(props)
// 初始化状态
this.state = {isHot: true}
// 解决changeWeather中this指向问题
this.changeWeather = this.changeWeather.bind(this)
}
// render调用几次? ——1+n次 1是初始化,n是状态更新的次数
render() {
// 读取状态
const {isHot} = this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}</h1>
}
changeWeather() {
// changeWeather放在哪里? ——Weather的原型对象上,供实例使用
// 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
// 类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
console.log(this)
const isHot = this.state.isHot
// 严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
this.setState({isHot: !isHot})
// 严重注意:状态(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>
生活是痛苦的白天,死亡是凉爽的夜晚。