组件核心实例属性 state
howcode 2022-08-04 0 React
# 组件实例核心属性 state
state
是组件实例对象最重要的属性,值为对象。又称为状态机,通过更新组件的 state
来更新对应的页面显示。
要点:
- 初始化
state
- React 中事件绑定
this
指向问题setState
修改state
状态constructor
、render
、自定义方法的调用次数
<script type="text/babel">
class Weather extends React.Component {
// 调用一次
constructor(props) {
super(props);
// 初始化 state
this.state = { isHot: true, wind: "微风" };
// 解决 this 指向问题
this.changeWeather = this.changeWeather.bind(this);
}
// 调用 1+N 次
render() {
// 读取状态
const { isHot } = this.state;
return (
<h1 onClick={this.changeWeather}>今天天气 {isHot ? "炎热" : "凉爽"}</h1>
);
}
// 点一次调一次
changeWeather() {
const isHot = this.state.isHot;
// 对 state 的修改是一种合并而非替换,即 wind 依然存在
this.setState({ isHot: !isHot });
}
}
ReactDOM.render(<Weather />, document.getElementById("test"));
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
简化版:
<script>
class Weather extends React.Component {
state = { isHot: true, wind: "微风" };
render() {
const { isHot } = this.state;
return (
<h2 onClick={this.changeWeather}>天气{isHot ? "炎热" : "凉爽"}</h2>
);
}
// 采用箭头函数 + 赋值语句形式
changeWeather = () => {
const isHot = this.state.isHot;
this.setState = { isHot: !isHot };
};
}
ReactDOM.render(<Weather />, document.getElementById("test"));
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
评论
- 表情
——暂无评论——