一、事件
在React中,组件的事件,本质上就是一个属性
按照之前React对组件的约定,由于事件本质上是一个属性,因此也需要使用小驼峰命名法
1、内置组件事件
import React from 'react';
import ReactDOM from 'react-dom';
function handleClick(e){
console.log("点击了!");
}
const btn = <button onClick={handleClick} onMouseEnter={(e)=>{
console.log("鼠标进入了!",e);
}}>按钮</button>
ReactDOM.render(btn, document.getElementById('root'));
2、自定义组件事件
//TickControl.js
import React, { Component } from 'react'
import MyComp from './MyComp'
export default class TickControl extends Component {
state = {
isOver: false
}
render() {
let status = "正在倒计时";
if(this.state.isOver){
status = "倒计时完成";
}
return (
<div>
<MyComp onOver={()=>{
this.setState({
isOver: true
})
}} time={6} />
<h2>{status}</h2>
</div>
)
}
}
//MyComp.js
import React, { Component } from 'react'
export default class MyComp extends Component {
constructor(props){
super(props);
this.state = {
time: props.time
}
const timer = setInterval(()=>{
this.setState({
time: this.state.time-1
})
if(this.state.time === 0){
clearInterval(timer);
this.props.onOver && this.props.onOver();
}
},800);
}
render() {
return (
<div>
倒计时: {this.state.time}
</div>
)
}
}
如果一个函数逻辑比较复杂的话,我们推荐先将函数封装好,直接绑定在属性上。
//TickControl.js
export default class TickControl extends Component {
state = {
isOver: false
}
handleOver(){
this.setState({
isOver: true
})
}
render() {
let status = "正在倒计时";
if(this.state.isOver){
status = "倒计时完成";
}
return (
<div>
<MyComp onOver={this.handleOver} time={6} />
<h2>{status}</h2>
</div>
)
}
}
但这里就有问题了(this的指向问题,在类组件中出现)。
此时handleOver是在当前对象原型上
react中,如果没有特殊处理,在事件处理函数中,this指向undefined
解决方法:
- 使用bind函数,绑定this,将方法绑定在当前对象上。
constructor(props){
super(props);
this.handleOver = this.handleOver.bind(this);
}
handleOver(){
this.setState({
isOver: true
})
}
或者
render() {
let status = "正在倒计时";
if(this.state.isOver){
status = "倒计时完成";
}
return (
<div>
<MyComp onOver={this.handleOver.bind(this)} time={6} />
<h2>{status}</h2>
</div>
)
}
2.箭头函数
我们前面写的就是,只是如果函数过于复杂,不方便阅读。那么我们进行改进。
handleOver = () => {
console.log(this);
this.setState({
isOver: true
})
}
博主开始运营自己的公众号啦,感兴趣的可以关注“飞羽逐星”微信公众号哦,拿起手机就能阅读感兴趣的博客啦!