<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>state</title>
<style>
.title {
background-color: orange;
width: 200px;
}
</style>
</head>
<body>
<!-- 准备好一个“容器” -->
<div id="test"></div>
<!-- 引入react核心库 -->
<script type="text/javascript" src="package/react.development.js"></script>
<!-- 引入react-dom,用于支持react操作DOM -->
<script type="text/javascript" src="package/react-dom.development.js"></script>
<!-- 引入babel,用于将jsx转为js -->
<script type="text/javascript" src="package/babel.min.js"></script>
<script type="text/babel">
class Wheather extends React.Component {
constructor(props){
super(props)
this.state = {isHot : false}
}
render() {
// console.log(this);
return (
<h1 onClick = {this.changeWeather}>今天天气真{this.state.isHot ? '炎热' : '凉爽'}</h1>
);
}
changeWeather() {
this.state.isHot = !this.state.isHot;
}
}
ReactDOM.render(<Wheather/>, document.getElementById('test'));
</script>
</body>
</html>
由于这段代码
onClick = {this.changeWeather}
只是将changeWeather这个函数赋值给点击事件的回调函数,并没有调用,所以changeWeather方法并不指向Weather实例,而回调函数的this默认是指向window的,而这边开启了babel严格模式,而且类中方法被自动开启了严格模式,所以会报undefined
解决方式是
constructor(props){
super(props)
this.state = {isHot : false}
this.changeWeather = this.changeWeather.bind(this);
}
案例
<script type="text/babel">
class Wheather extends React.Component {
constructor(props){
super(props)
this.state = {isHot : false}
this.changeWeather = this.changeWeather.bind(this);
}
render() {
return (
<h1 onClick = {this.changeWeather}>今天天气真{this.state.isHot ? '炎热' : '凉爽'}</h1>
);
}
changeWeather() {
const isHot = this.state.isHot;
// react不支持手动更改state,必须通过内置api setState来进行更改
this.setState({isHot:!isHot});
}
}
ReactDOM.render(<Wheather/>, document.getElementById('test'));
下边是简写形式
class Weather extends React.Component {
// 初始化状态
state = {isHot : false};//赋值语句,相当于在Weather实例对象身上添加了一个新的属性state
render() {
return (
<h1 onClick = {this.changeWeather}>今天天气真{this.state.isHot ? '炎热' : '凉爽'}</h1>
);
}
changeWeather = () => {//赋值语句,相当于在Weather实例对象身上添加了一个新的属性changeWeather
const isHot = this.state.isHot;
// react不支持手动更改state,必须通过内置api setState来进行更改
this.setState({isHot:!isHot});
}
}
// 渲染组件到页面上
ReactDOM.render(<Weather/>, document.getElementById('test'));