<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setState</title>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<!-- 准备一个容器 -->
<div id="test"></div>
</body>
<script type="text/babel">
//定义类组件
class MyComponent extends React.Component {
//构造器只会调用一次
constructor(props) {
super(props)
//状态初始化
this.state = {
isDog: true,
color: '黑色'
}
this.changeAnimal = this._changeAnimal.bind(this)
}
//render会调用1+n次,第一次是初始化,后续是state中数据改变时调用
render() {
const { isDog, color } = this.state
return (
//React中的事件要写成大驼峰的形式;这里使用{}来写,里面不能有括号,否则会直接执行
<div onClick={this.changeAnimal}>
<h1>
<span>这是一只{isDog ? '狗' : '猫'},颜色是{color}</span>
</h1>
</div>
)
}
_changeAnimal() {
const isDog = this.state.isDog
//setState是对state进行合并,而不是替换掉原来的state,简单来说就是只做修改
this.setState({isDog: !isDog})
}
}
//react渲染
ReactDOM.render(<MyComponent />, document.getElementById("test"))
/*
总结:
1.在类中声明函数无法作为回调函数使用,因为类中的方法会开启局部的严格模式,会让它丢失this。如_changeAnimal()
2.想要操作state中的数据,必须使用setState()方法,直接操作React不会进行处理
3.想要使用类中声明的函数作为回调函数,需要在构造器中使用bind()方法传入实例对象的this生成新的函数
4.React中的事件要写成大驼峰的形式;使用{}来写,且函数不能携带括号,否则会直接执行
*/
</script>
</html>