1。点击div里的的文字,天气在“炎热”和“寒冷”之间切换
点击之前:
点击之后:
<script type="text/babel">
class Demo extends React.Component{
constructor(props){
super(props)
this.state = {
isHot:false
}
}
clickFun = () => { //注意这里的函数式箭头函数,所以解决了this烦恼,如果不是this函数那就需要绑定this指向
console.log('--',this);
this.setState({
isHot: !this.state.isHot //取反
})
}
render(){
console.log(this.state.isHot);
//render放在哪里?—— Demo的原型对象上(可以再控制台输出看Demo.prototype),供实例使用
//render的this是谁?——Demo的实例对象 Demo组件实例对象 demo的实例对象是渲染函数new出来的,并通过它去调用原型上的render方法
console.log('render的this:',this);
return(
<h2 onClick={this.clickFun}>今天天气很<span >{this.state.isHot?'炎热':'寒冷'}</span></h2>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
要改state里的值只能用this.setState({ })来改,
要用的时候可以直接this.state.xx,或者先解构const{xx} = this.state