注意:
- 初始化状态——this.state={}
- bind()可改变this指向,需要赋值
- changeWeather放在哪里? - Weather的原型对象上,供实例使用
- 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
- 类中方法默认开启局部严格模式,所以changeWeather中的this为undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--准备好一个容器-->
<div id="test"></div>
<!--引入react核心库-->
<script src="../js/react.development.js"></script>
<!--引入react-dom,用于支持react操作dom-->
<script src="../js/react-dom.development.js"></script>
<!--引入babel,用于将jsx转为js-->
<script src="../js/babel.min.js"></script>
<script type="text/babel">
// 两个***代表的this不一样,前者代表Weather这个类,后者指向的是window
// 1.创建组件
class Weather extends React.Component {
constructor(props) {
super(props);
// 初始化状态
this.state = {isHot:false}
// 改变this指向
this.changeWeather = this.changeWeather.bind(this)
// ***
}
render() {
// 读取状态
const {isHot} = this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot?'炎热':'凉爽'}</h1>
}
changeWeather() {
// changeWeather放在哪里? - Weather的原型对象上,供实例使用
// 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
// 类中方法默认开启局部严格模式,所以changeWeather中的this为undefined
console.log(this.state.isHot);
const isHot = this.state.isHot
// 注意:状态(state)不能直接更改,下边这行就是直接更改!!
this.isHot = !this.isHot
// 应该这么改!!用setState
this.setState({isHot:!isHot})
// ***
}
}
// 2.渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
</body>
</html>