[React05]组件实例三大核心属性之一:状态state
上一节介绍,组件分为函数式组件和类式组件,但是状态这一属性是组件实例的,而只有类式组件才能被实例化,因此是针对类式组件来说的。
想要实现效果:
点击实现两个的切换
简单版本,可以通过修改代码中state的true或者false来修改页面中的炎热和凉爽。
//1、创建类式组件
class Weather extends React.Component{
constructor(props){
super(props);
this.state = {isHot:false}
}
render(){
return <h2>今天天气很{this.state.isHot? '炎热':'凉爽'}</h2>
}
}
//2、渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'));
但是原本的案例是希望在点击事件之后来切换,因此,还需要添加一个点击事件。
//1、创建类式组件
class Weather extends React.Component{
constructor(props){
super(props);
//初始化状态
this.state = {isHot:false}
//解决changeWeather中的this指向问题
this.changeState = this.changeWeather.bind(this)
}
render(){
const{isHot}=this.state
return <h2 onClick={this.changeState}>今天天气很{this.state.isHot? '炎热':'凉爽'}</h2>
}
changeWeather(){
const isHot = this.state.isHot;
//使用setState()方法
this.setState({isHot:!isHot})
//此写法错误,状态不能直接修改
//this.state.isHot=!isHot
}
}
//2、渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'));
即可实现点击切换的效果。
在state里加一个属性,发现setState方法更新是合并,而不是覆盖。
//1、创建类式组件
class Weather extends React.Component{
constructor(props){
super(props);
//初始化状态
this.state = {isHot:false,wind:'微风'}
//解决changeWeather中的this指向问题
this.changeState = this.changeWeather.bind(this)
}
render(){
const{isHot,wind}=this.state
return <h2 onClick={this.changeState}>今天天气很{isHot? '炎热':'凉爽'},{wind}</h2>
}
changeWeather(){
const isHot = this.state.isHot;
//使用setState()方法
this.setState({isHot:!isHot})
//此写法错误,状态不能直接修改
//this.state.isHot=!isHot
}
}
//2、渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'));
其中,构造器只调用了一次,render构造了1+n次,n是状态更新的次数。
但这么写过于繁琐,先学习将state写法进行精简。
//1、创建类式组件
class Weather extends React.Component{
//初始化状态
state = {isHot:false,wind:'微风'}
render(){
const{isHot,wind}=this.state
return <h2 onClick={this.changeState}>今天天气很{isHot? '炎热':'凉爽'},{wind}</h2>
}
//自定义方法---要用赋值语句的形式+箭头函数
changeState = ()=>{
const isHot = this.state.isHot;
this.setState({isHot:!isHot})
}
}
//2、渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'));
总结:
- state是最重要的属性,它的值是一个对象。
- 组件中render方法中的this是实例对象。
- 组件中自定义方法的this为undefined。可以通过两种方式。第一个是强制绑定,通过函数对象的bind();第二种是通过箭头函数。
学习B站React笔记【自用】