如何访问滚动处理程序的事件?无法访问offsetTop,scrollTop等
class App extends React.Component {
handleScroll = e => {
console.log(e.target.scrollTop);
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
render() {
return (
<div>
<h1 style={{ height: "1000px" }}>Hello CodeSandbox</h1>
<h1>Hello end</h1>
</div>
);
}
}
答案 0 :(得分:0)
您仍然可以访问传统的窗口方法,以帮助确定是否到达底部。这是您更新的代码和沙盒:https://codesandbox.io/s/hardcore-poitras-04g3h
当到达底部时,我们可以使用状态来配置组件的外观。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
endReached: false
};
handleScroll = () => {
if (
window.scrollY + window.innerHeight >= document.body.offsetHeight &&
!this.state.endReached
) {
this.setState({
endReached: true
});
} else {
this.setState({
endReached: false
});
}
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
render() {
return (
<div className={this.state.endReached ? "end-reached" : ""}>
<h1 style={{ height: "1000px" }}>Hello CodeSandbox</h1>
<h1>Hello end</h1>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
答案 1 :(得分:0)
您可以使用document.documentElement
来访问scrollTop
:
class App extends React.Component {
handleScroll = e => {
console.log(document.documentElement.scrollTop);
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
render() {
return (
<div>
<h1 style={{ height: "1000px" }}>Hello CodeSandbox</h1>
<h1>Hello end</h1>
</div>
);
}
}
答案 2 :(得分:0)
尝试此代码。希望它能起作用。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
handleScroll = e => {
const winScroll =
document.body.scrollTop || document.documentElement.scrollTop;
console.log("scrolled=========>", winScroll);
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.listenToScroll);
}
render() {
return (
<div>
<h1 style={{ height: "1000px" }}>Hello CodeSandbox</h1>
<h1>Hello end</h1>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);