由于某种原因,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
答案 0 :(得分:2)
您无法在其中传递多种事件类型。试试这个:
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);
}
答案 1 :(得分:0)
constructor(props) {
super(props)
this.selector = document.querySelector(selector)
this.state = {
zeroSum: 0,
}
this.getVisible.bind(this) // bind all your class methods to this
}