State是组件对象最重要的属性,值是对象可以包含多个key-value的组合
组件被称为状态机,通过更新组件的state来更新对应的页面显示
组件中的render方法中的this为组件实例对象
组件自定义的方法中this为undefined解决办法:
状态数据,不能直接修改或更新
制作一个点击就能够实现文字发生变化的实例,千言万语都在注释里了
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<div id="test">div>
<script src="../js/react.development.js">script>
<script src="../js/react-dom.development.js">script>
<script src="../js/babel.min.js">script>
<script type="text/babel">
//类式组件
class Weather extends React.Component {
constructor(props){
super(props)
this.state = {isHot:false, wind:"微风"}
//解决change中的this指向问题
this.changeWeather = this.change.bind(this)
}
change(){
//由于changeWeather是在onClick的回调,所以不是通过实例调用的,式直接调用
//类中的方法默认开启了局部严格模式,所以changeWeather中的this为undefined
//状态不可直接更改,下面为直接更改
// this.state.isHot = !this.state.isHot
//状态必须通过setState进行
//更新,而不是替换
this.setState({isHot:!this.state.isHot})
}
render() {//供实例使用
const {isHot, wind} = this.state
return <h2 onClick={this.changeWeather}>今天天气很{isHot ? "炎热":"凉爽"}, {wind}</h2>
}
}
//react发现组件是类,则new出该类的实例,并通过该实例调用到原型上的render方法
ReactDOM.render(<Weather/>, document.getElementById("test"))
script>
body>
html>
运行结果:

点击即可变化

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<div id="test">div>
<script src="../js/react.development.js">script>
<script src="../js/react-dom.development.js">script>
<script src="../js/babel.min.js">script>
<script type="text/babel">
//类式组件
class Weather extends React.Component {
state = {isHot:false, wind:"微风"}
// 自定义方法
change = () => {
this.setState({isHot:!this.state.isHot})
}
render() {
const {isHot, wind} = this.state
return <h2 onClick={this.changeWeather}>今天天气很{isHot ? "炎热":"凉爽"}, {wind}</h2>
}
}
//react发现组件是类,则new出该类的实例,并通过该实例调用到原型上的render方法
ReactDOM.render(<Weather/>, document.getElementById("test"))
script>
body>
html>
和完整版的结果一样,不过使用箭头函数会简介很多