您好,我正在尝试检查用户是否滚动了页面的底部。
我正在使用此功能进行检查:
const handleScroll = (event) => {
const bottom = event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight;
if(bottom){
console.log('hello');
}
}
但是问题是我的应用程序看起来像这样:
现在,该功能仅在内部滚动条位于底部时才起作用。但是我希望它在外部滚动条到达底部时触发。
整个代码如下:
const handleScroll = (event) => {
const bottom = event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight;
if(bottom){
console.log('hello');
}
}
return (
<div className='main' onScroll = {handleScroll}>
<div className='project-counter'>{filteredProjects.length > 0 ? (<p>Gevonden projecten : {filteredProjects.length}</p>) : null}</div>
{pro.map(project => (
<div className='view-container' key={project._id}>
<div className='hours-container'>
<table>
<tr>
<th className='tb-first'>Datum</th>
<th className='tb-first'>medewerker</th>
<th>Dienst</th>
<th>Toelichting</th>
<th>Aantal</th>
</tr>
{project.projectHours.map(hour => (
<tr>
<td>{hour.created_at}</td>
<td>{hour.employee.name}</td>
<td>{hour.type.label}</td>
<td>{hour.note}</td>
<td>{hour.hours.toFixed(2)}</td>
</tr>
))}
</table>
</div>
</div>
))}
</div>
)
答案 0 :(得分:1)
将侦听器添加到窗口对象:
const App = () => {
const handleScroll = () => {
const bottom = Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
if (bottom) {
console.log('at the bottom');
}
};
React.useEffect(() => {
window.addEventListener('scroll', handleScroll, {
passive: true
});
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return <div className = "?" > ? < /div>
};
ReactDOM.render( < App / > , document.getElementById("root"));
.? {
height: 200vh;
width: 100%;
background-color: mediumseagreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.development.js"></script>
<div id="root"></div>
答案 1 :(得分:0)
对我来说,您的内部滚动条似乎属于您的div
。您的组件水平更高吗?尝试在浏览器的开发模式(F12)中找到外部滚动条,并查看其所属的元素。如果这是另一个div元素,则只需将带有功能handleScroll
的侦听器添加到该元素。