React类组件和函数组件中this的处理
先说类组件
类组件中的this比较烦人,指向问题比较感人,昨天在项目中监听函数里面又调用了其他函数的时候,this指向发生问题
所以在类组件中,使用addEventListener添加事件监听的时候使用箭头函数 解决this指向问题
代码如下
import React, { Component } from 'react'
export default class A extends Component {
constructor() {
super()
// 移除监听事件的时候需要解绑
this.watcher = this.watcher.bind(this)
}
watcher () {
console.log('点击调用')
this.innerFn()
console.log('点击调用')
}
innerFn () {
console.log('innerFN')
}
componentDidMount () {
// 这里的watcher方法调用了另外一个函数,所以需要使用箭头函数修改watcher方法里面的this指向
document.addEventListener('click', () => this.watcher())
}
componentWillUnmount () {
console.log('移除')
document.removeEventListener('click',this.watcher)
}
render () {
return (
<div id='big'>
这是一大段文字
这是一大段文字
这是一大段文字
这是一大段文字
</div>
)
}
}
在hooks组件中没有这些生命周期函数
import React from 'react' import { useState, useEffect } from 'react' export default function TapNum () { const [age, setAge] = useState(0) function showed () { console.log('showed') } function hidden () { console.log('hidden') } function pageWatcher () { if (document.hidden) { hidden() } else { showed() } } useEffect(() => { // 这里直接移除监听函数因为useEffect外层直接是箭头函数 window.addEventListener('visibilitychange', pageWatcher) return () => { window.removeEventListener('visibilitychange', pageWatcher) console.log('取消监听') } }) // const handleClick = () => { // setNum(num + 1) // } return ( <div> <p>{age}</p> {/* <button onClick={handleClick}>+</button> */} </div> ) }

浙公网安备 33010602011771号