新手咋地

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
<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> </head> <body> <!-- 准备好一个容器 --> <div id="test"></div>
<!-- 引入react核心库 -->
<script src="../js/react.development.js"></script>
<!-- 引入react-dom,用于支持react操作dom -->
<script src="../js/react-dom.development.js"></script>
<!-- 引入babel,用于将jsx转为js -->
<script src="../js/babel.min.js"></script>

<script type="text/babel">
    // 1. 创建DOM
    class Weather extends React.Component {

        // 构造器调用几次? —— 1次
        constructor(props) {
            console.log('constructor')
            super(props)
            this.state = { isHot: true, wind: '微风' }
            this.changeWeather = this.changeWeather.bind(this)
        }

        // render调用几次? —— 1+n次 n是状态更新的次数
        render() {
            console.log('render')
            // 读取状态
            const { isHot, wind } = this.state;
            return <h1 onClick={this.changeWeather} >今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
        }

        // changeWeather调用几次? —— 点几次调几次
        changeWeather() {
            // changeWeather放在那里?——Weather的原型对象上,供实例使用
            // 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
            // 类的方法默认开启了局部严格模式,所以changeWeather中的this为undefined
            // console.log(this);//指向实例对象 

            const isHot = this.state.isHot;
            // 严重注意:状态(state)不可直接更改,下面这行就是直接更改
            // this.state.isHot = !isHot

            // 严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换
            this.setState({ isHot: !isHot });
        }

    }
    // 2.渲染组件到页面
    ReactDOM.render(<Weather />, document.getElementById('test'))

</script>
</body>
posted on 2021-11-22 16:15  新手咋地  阅读(42)  评论(0)    收藏  举报