欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

React之setState使用

发布时间:2024/9/27 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。