React之setState使用
<!DOCTYPE html>
<html>
<head>
<meat charset="UTF-8">
<title>React之setState使用</title>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="test"></div>
<!-- 核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- react-dom,操作dom -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 引入babel,jsx转为js -->
<script type="text/javascript" src="../js/babel.min.js"></script>
<!-- 此处一定要写babel -->
<script type="text/babel">
//1.创建组件
class Weather extends React.Component{
//构造器调用几次?——1次
constructor(props){
console.log('constructor')
super(props)
this.state={isHot:false,wind:'微风'}
this.demo=this.test.bind(this) //test为Weather中的 test(),demo在31行使用
}
//render调用几次?——1+n次,1是初始化,n是状态更新次数
render(){
console.log('render')
const {isHot,wind} =this.state;
console.log(this);
return <h1 onClick={this.demo}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
}
//test调用几次?——点几次调几次
test() {
console.log('test')
//changeWeather放在哪里?————weather的原型对象上,供实例使用
//changeWeather作为onClick的回调,所有不是通过实例调用的,是直接调用
//类中的方法默认开启了局部的严格模式,所有changeWeather中的this为underfined
const isHot=this.state.isHot
//严重注意:状态必须通过setState进行更新,是合并,不是替换
this.setState({isHot:!isHot})
//注意:state不可直接更改,下面这行是直接更改
// this.state.isHot=!isHot//错误写法
}
}
//2.渲染组件到页面
ReactDOM.render(<Weather />, document.getElementById('test'));
</script>
</body>
</html>
总结
以上是生活随笔为你收集整理的React之setState使用的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: php:// 协议
- 下一篇: React之解决类中的this