react基础 react组件事件

组件事件

在 react 中,组件的事件本质上就是一个属性。

会在特定的时间运行相对应的函数。

如果没有特殊处理,在事件处理函数中,this 指向 undefined

处理方法

  1. 使用 bind 函数,绑定 this
1
<Tick number={10} onOver={this.handleOver.bind(this)}></Tick>
  1. 使用箭头函数
1
2
3
4
5
6
handleOver = () => {
this.setState({
isOver: true,
});
};
<Tick number={10} onOver={this.handleOver}></Tick>;

内置组件

1
2
3
4
5
6
7
<button
onClick={function () {
console.log("点击了!");
}}
>
点我
</button>
1
2
3
4
5
function handleClick() {
console.log("点击了!");
}

<button onClick={handleClick}>点我</button>;

自定义组件

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
29
import React, { Component } from "react";

// 倒计时组件
export default class Tick extends Component {
// // 初始化组件
// state = {
// lastTime: this.props.number,
// };
constructor(props) {
super(props);
// 初始化组件
this.state = {
lastTime: props.number,
};
const timer = setInterval(() => {
this.setState({
lastTime: this.state.lastTime - 1,
});
if (this.state.lastTime === 0) {
clearInterval(timer);
//倒计时完成
this.props.onOver && this.props.onOver(); //结束事件
}
}, 1000);
}
render() {
return <div>倒计时:{this.state.lastTime}</div>;
}
}
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
import React, { Component } from "react";
import Tick from "./Tick";

export default class TickOver extends Component {
state = {
isOver: false,
};
// 处理倒计时结束的事件
handleOver() {
this.setState({
isOver: true,
});
}

render() {
let content = "正在倒计时";
if (this.state.isOver) {
content = "倒计时结束了";
}
return (
<div>
<Tick number={10} onOver={this.handleOver.bind(this)}></Tick>
<h2>{content}</h2>
</div>
);
}
}