美文网首页
react学习(12)state的简写和总结

react学习(12)state的简写和总结

作者: 哆啦C梦的百宝箱 | 来源:发表于2022-08-15 10:57 被阅读0次
<script type="text/babel">
        class Weather extends React.Component {
            state={isHot:false};
            render(){
                return <h1 onClick={this.change}>今天天气很{this.state.isHot?'炎热':'凉爽'}</h1>
            }
            change=()=>{
                this.setState({isHot:!this.state.isHot});
            }
        }
        ReactDOM.render(<Weather/>,document.getElementById('test'));
    </script>

1: 可以不把state写到构造器函数中,直接使用赋值语句,state也同样存在于组件类的实例上。
2:state是组件对象最重要的属性,值是对象。
3:被称为"状态机",通过更新组件的state,来更新对应的页面显示(重新渲染组件)
4:组件中render方法的this是组件的实例对象。
5:组件自定义的方法,this是undefined,解决方法:

  • a:使用箭头函数的方式
  • b:使用bind方法

相关文章

网友评论

      本文标题:react学习(12)state的简写和总结

      本文链接:https://www.haomeiwen.com/subject/zyaxgrtx.html