我正在尝试在由3 div组成的React中构建一个网页。我想要的是,当用户滚动到rose div的底部时,应该出现一个标头(带有粘性位置)。
这是我的代码:
interface IState {}
export class App extends React.Component<{}, IState> {
handleScroll = e => {
const bottom =
e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
console.log("bottom!");
}
};
render() {
return (
<div>
<div
className="w-100"
style={{ height: 1200, backgroundColor: "#ebdec3" }}
/>
<div
className="w-100 h-100"
style={{ backgroundColor: "#e8dae7" }}
onScroll={this.handleScroll}
>
Lorem ipsum dolor sit amet...
</div>
<div
className="w-100"
style={{ height: 1200, backgroundColor: "#d3e3e1" }}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));
我还创建了一个sandbox。
我尝试使用onScroll事件,但没有任何显示。
我遵循this example。
为什么?我需要一些帮助
最佳答案
按照您链接的示例,我在沙盒中创建了一个有效的解决方案here。
interface IState { }
export class App extends React.Component<{}, IState> {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
this.targetDiv = React.createRef();
}
handleScroll = e => {
// const bottom = (e.target.scrollHeight - e.target.scrollTop) === e.target.clientHeight;
const bottom =
this.targetDiv.current.getBoundingClientRect().bottom <=
window.innerHeight;
if (bottom) {
console.log("bottom!");
}
};
componentDidMount() {
document.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
document.removeEventListener("scroll", this.handleScroll);
}
render() {
return (
<div>
<div
className="w-100"
style={{ height: 1200, backgroundColor: "#ebdec3" }}
/>
<div
className="w-100 h-100"
style={{ backgroundColor: "#e8dae7" }}
ref={this.targetDiv}
// onScroll={this.handleScroll}
>
Lorem ipsum ...
</div>
<div
className="w-100"
style={{ height: 1200, backgroundColor: "#d3e3e1" }}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));
您需要在
componentDidMount
方法中将滚动事件绑定到侦听器。另外,您可以使用ref
获得目标div。
关于javascript - 用户滚动到特定div的底部时,标题应显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57801633/