<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
<script type="text/babel">
//www.bind({a:1,b:2}) 返回的是一个函数
class Weather extends React.Component{
constructor(props) {
super(props);
this.state ={
isHot:true,
wind:'微风'
}
/*//此时
this.abc= abc是你需要用的事件名
this.changeWeather changeWeather 是在这个类中定义的事件
.bind(this) //www.bind({a:1,b:2}) 返回的是一个函数
*/
this.abc=this.changeWeather.bind(this)
}
render() {
const state =this.state
console.log(this) //是本身
return (
<h1 onClick={this.abc}>今天天气很{state.isHot ? '炎热' : '凉爽'},{state.wind}</h1>
)
}
changeWeather() {
console.log(this.state.isHot);
/*
//注意state状态不可以直接更改 下面的就是直接更改(错误的写法)
this.state.isHot = !this.state.isHot
*/
//要用setState
const state =this.state
//下面代码执行后会再次调用一次render()
this.setState({
isHot : !state.isHot,
})
if (state.isHot ===true){
this.setState({
wind: '微风'
})
}else {
this.setState({
wind: '大风'
})
}
}
}
ReactDOM.render(<Weather/>,test)
</script>