代码
<!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
指向问题
- 类里的方法默认开启
局部严格模式
,因此直接调用类里的方法this
为undefined
- 当把类里的方法直接绑定给事件时,方法直接调用,
this
为undefined
,不能访问到组件实例 - 因此通过
bind
方法来绑定this
指向
- 事件绑定问题
-
事件名需要写成驼峰形式 例如:
onclick
写成onClick
-
绑定的回调与传统相比,应该是回调本身,而不是回调的执行
// 传统方式,直接对回调执行 <h1 onclick="changeWeather()"></h1> // JSX方式,传入回调本身即可 <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}. {wind}</h1>
-
React
对事件进行改写,如:onxxx
改成onXxx
,是为了更好的兼容性 -
React
中的事件通过事件委托,委托给组件最外层的元素,是为了更高效
- 属性更新问题
- 更新
state
需要使用setState
方法 -
setState
是合并更新,而不是替换更新