三大核心属性分别是:state、props、refs
state属性
- state是组件对象最重要的属性, 值是对象(可以包含多个key-value的组合)
- 组件被称为"状态机", 通过更新组件的state来更新对应的页面显示(重新渲染组件)
先附上整体实例原码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>state</title>
</head>
<body>
<!--准备好一个容器-->
<div id="test"></div>
<!--引入react核心库-->
<script type="text/javascript" src="../js/react.development.js"></script>
<!--引入react-dom,用于支持react操作DOM-->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!--引入babel,用于将jsx转为js-->
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel"> //<!--此处一定要写babel-->
// <!-- 1.创建组件 -->
class Weather extends React.Component{
//构造器调用几次? --------1次
constructor(props){
super(props)
//初始化状态
this.state = {isHot:true,WindScale:false}
//解决changeWeather中this指向问题
this.demo=this.changeWeather.bind(this) //bind返回一个函数,这里的demo相当于一个函数
}
//render调用几次? ---------1+n次 1是初始化的那次 n是setState状态更新的次数
render(){
//读取状态
const {isHot} =this.state
const {WindScale} =this.state
return <h1 onClick={this.demo}>今天天气很{isHot ? 'hot' : 'cold'},today is {WindScale ? 'big' : 'small'} wind</h1>
}
//changeWeather调用几次? ----------点几次调用几次
changeWeather(){
//由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
//类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
//console.log(this);
//获取原来的isHot值
const isHot=this.state.isHot
const WindScale=this.state.WindScale
//严重注意:状态(state)不可直接更改,下面这行就是直接更改!
//this.state.isHot=!isHot
//严重注意:状态必须通过setState进行更改,且更新是一种合并,不是替换。
this.setState({isHot:!isHot})
this.setState({WindScale:!WindScale})
}
}
//<!-- 2.渲染组件到页面 -->
ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
</body>
</html>
需要注意的:
- 构造器必须写super(props),且必须在调用的this对象前。
- 使用bind()函数解决this对象的指向问题。
- 状态(state)不可直接更改,状态必须通过setState进行更改,且更新是一种合并,不是替换!
state属性精简版(用箭头函数):
<script type="text/babel"> //<!--此处一定要写babel-->
class Weather extends React.Component{
//constructor(props){
//super(props)
// this.state = {isHot:true,WindScale:false}
// this.demo=this.changeWeather.bind(this)
//}
state = {isHot:true,WindScale:false}
render(){
const {isHot,WindScale} =this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot ? 'hot' : 'cold'},today is {WindScale ? 'big' : 'small'} wind</h1>
}
//自定义方法---要用赋值语句的形式+箭头函数
changeWeather = ()=>{
const isHot=this.state.isHot
const WindScale=this.state.WindScale
this.setState({isHot:!isHot})
this.setState({WindScale:!WindScale})
}
}
ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>