初始版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
<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>
<script type="text/babel">
class Weather extends React.Component {
constructor(props) {
super(props);
this.state = {isHot: true};
this.changeWeather = this.changeWeather.bind(this); // changeWeather中可以 通过 this 调用组件 实例
}
render(h) {
let {isHot} = this.state;
return (
<div onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '寒冷'}</div>
)
}
changeWeather() {
let { isHot } = this.state;
this.setState({isHot: !isHot});
}
}
ReactDOM.render(<Weather/>, document.getElementById('app'));
</script>
</html>
上边版本,每增加一个方法,都需要在 constructor中使用bind绑定一次,太繁琐,
变动点:
- 无需 constructor,state直接赋值,后续也可通过 this.state 取值;
- 无需在 constructor 中使用bind 绑定时间的this,直接使用箭头函数赋值给函数变量,即可在该函数内使用 this 获取 组件实例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
<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>
<script type="text/babel">
class Weather extends React.Component {
state = {isHot: true}; // state 挂在 实例下,可通过 this.state 获取
render(h) {
let {isHot} = this.state;
return (
<div onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '寒冷'}</div>
)
}
changeWeather = () => { // 箭头函数内部的 this 指向箭头函数创建时的 this,也就是 Weather组件实例,所以不再需要 使用 bind 绑定
let { isHot } = this.state;
this.setState({isHot: !isHot});
}
}
ReactDOM.render(<Weather/>, document.getElementById('app'));
</script>
</html>