gpt4 book ai didi

javascript - React添加/删除事件监听器

转载 作者:行者123 更新时间:2023-12-01 02:46:39 26 4
gpt4 key购买 nike

由于某种原因,this.getVisible() 不会在滚动/调整大小事件上触发。谁能告诉我问题出在哪里?

import React, { Component } from 'react'

const ZeroSum = ({
selector,
...passedProps,
}) => WrappedComponent => class WithZeroSum extends Component {
constructor(props) {
super(props)
this.selector = document.querySelector(selector)
this.state = {
zeroSum: 0,
}
}

componentWillMount() {
window.addEventListener('scroll resize', () => this.getVisible())
this.getVisible()
}

componentWillUnmount() {
window.removeEventListener('scroll resize', () => this.getVisible())
}

getVisible() {
const vHeight = document.documentElement.clientHeight
const eTop = this.selector.getBoundingClientRect().top
return this.setState({ zeroSum: Math.max(0, vHeight - eTop) })
}

render() {
const { zeroSum } = this.state
const props = { ...this.props, ...passedProps }
console.log(zeroSum)
return <WrappedComponent {...props} zeroSum={zeroSum} />
}
}

export default ZeroSum

最佳答案

您不能在其中传递多个事件类型。试试这个:

constructor(props) {
// ...
this.state = {
// ...
listener: this.getVisible.bind(this)
};
}

componentWillMount(){
window.addEventListener("scroll", this.state.listener);
window.addEventListener("resize", this.state.listener);
this.state.listener();
}

componentWillUnount(){
window.removeEventListener("scroll", this.state.listener);
window.removeEventListener("resize", this.state.listener);
}

关于javascript - React添加/删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com