代码

<!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="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>
</head>
<body>
    <div id="app"></div>
    <script type="text/babel">
        class Weather extends React.Component {
        	// 只在创建组件实例时执行 1 次
            constructor () {
                super()
                console.log('constructor')
                this.state = {isHot: false, wind: '微风'}
                this.changeWeather = this.changeWeather.bind(this)
            }
            // 执行 1 + n 次,1 是初次渲染,n 是更新的次数
            render () {
                console.log("render")
                const {isHot, wind} = this.state
                return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}. {wind}</h1>
            }
            // 执行 n 次, n是事件触发的次数
            changeWeather () {
                console.log('changeWeather')
                const {isHot} = this.state
                this.setState({isHot: !isHot})
            }
        }
        ReactDOM.render(<Weather/>, document.getElementById('app'))
    </script>
</body>
</html>

注意事项

  • this指向问题
  1. 类里的方法默认开启局部严格模式,因此直接调用类里的方法thisundefined
  2. 当把类里的方法直接绑定给事件时,方法直接调用,thisundefined,不能访问到组件实例
  3. 因此通过bind方法来绑定this指向
  • 事件绑定问题
  1. 事件名需要写成驼峰形式 例如:onclick 写成 onClick

  2. 绑定的回调与传统相比,应该是回调本身,而不是回调的执行

    // 传统方式,直接对回调执行
    <h1 onclick="changeWeather()"></h1>
    // JSX方式,传入回调本身即可
    <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}. {wind}</h1>
    
  3. React 对事件进行改写,如:onxxx 改成 onXxx ,是为了更好的兼容性

  4. React 中的事件通过事件委托,委托给组件最外层的元素,是为了更高效

  • 属性更新问题
  1. 更新 state需要使用setState方法
  2. setState是合并更新,而不是替换更新