0
点赞
收藏
分享

微信扫一扫

react框架之 state属性学习

兮城 2022-04-27 阅读 28

一。state是组件实例的三大核心属性之一
它通常在类式组件中比较常用,在函数组件中通过hooks可以使用

  //函数组件
        function Demo(){
            return  <h>dhsh</h>
        }
        ReactDOM.render(<Demo/>,document.getElementById('test'));
        //类式组件
        class Mycomponent extends React.Component{
         render(){
             return <div>niha </div>
         }

        };
        ReactDOM.render(<Mycomponent/>,document.getElementById('io'))

二,着重看一下在类式组件中的使用,
可以在类式组件的构造函数中声名赋值 this.state,state值为对象(可以包含多个key-value的组合)

 constructor(props) {
                super(props);
                this.state={ishot:false,head:true}
                this.changeWeather=this.changeWeather.bind(this)
            }```
   应用:通过判断它的属性值去确定值的生成,下面在类中的render()函数中定义个值的判断问题,render函数绑定在class类的原型上,当生成类的实例对象时,实例对象就调用了render函数
   

```javascript
 render(){
                const {ishot}=this.state;
                return <h1 onClick={this.changeWeather}>今天天气很{ishot?"很热":"凉爽"}</h1>
            };
            changeWeather(){
                const ishott= this.state.ishot
               this.setState({ishot:!ishott})
            }

声名了一个函数去改变state的值,它的值只能通过setstate()函数改变,不能直接改变,它的改变不是重新赋值,是合并,然后在render函数中调用changeweather函数,但是在render函数中调用这个函数属于直接执行,不能获取类中state的值,所以在类的构造函数中,通过bind()方法改变this指向。
最终效果,点击h1标签页可以改变字体内容
三总结
具体代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
    <div id="er"></div>
    <script type="text/babel">
        //改变this指向问题
        class Weather extends React.Component{
            constructor(props) {
                super(props);
                this.state={ishot:false}
                this.changeWeather=this.changeWeather.bind(this)
            }
            
            render(){
                const {ishot}=this.state;
                return <h1 onClick={this.changeWeather}>今天天气很{ishot?"很热":"凉爽"}</h1>
            };
            changeWeather(){
                const ishott= this.state.ishot
               this.setState({ishot:!ishott})
            }
        } 
        ReactDOM.render(<Weather/>,document.getElementById("er"));

    </script>
</body>
</html>

实现效果
在这里插入图片描述
点击之后
在这里插入图片描述

举报

相关推荐

0 条评论