【问题标题】:Scroll Position in react js反应js中的滚动位置
【发布时间】:2022-11-23 00:51:06
【问题描述】:

我想在 React js 中获取 div 的滚动位置。我尝试让窗口滚动值值始终为 0。

`

handleScrollPosition(e){
console.log("inside handle scroll")
    console.log(window.scrollX,window.scrollY)
}



<SearchListWrapper className="TestSL"   onScroll={this.handleScrollPosition} >

`

【问题讨论】:

  • 您可能想要创建 ref const ref = useRef&lt;HTMLDivElement&gt;(); 并将其传递给 &lt;SearchListWrapper ref={ref},然后处理访问 ref.current.scrollXref.current.scrollY 的 onScroll 事件。为此,必须将 SearchListWrapper 定义为 React.forwardRef(...) 组件

标签: javascript reactjs react-native react-hooks


【解决方案1】:

如果你想要页面的滚动位置,你正在做的事情应该有效,但提醒你,在滚动整个页面高度之前你不会滚动。

如果你想获得元素相对于页面的位置,你可以使用以下方法:getBoundingClientRect().top。在 JavaScript 中,这与以下内容一起使用:

document.getElementById(element).getBoundingClientRect().top;

但正如您在 React 中一样,您不应该以这种方式引用元素。您应该使用 useRef 给您想要位置的元素,然后使用

yourRef.current.getBoundingClientRect().top

所以这个例子是:

export default function App() {
  const divRef = React.useRef();
  if (divRef) {
    console.log(divRef.current.getBoundingClientRect().top);
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2> Start editing to see some magic happen!</h2>
      <div ref={divRef}>Text</div>
    </div>
  );
}

此解决方案的替代方案在这里:Get scroll position with Reactjs

【讨论】:

    【解决方案2】:

    解决方案

    handleScrollPosition(e){
        const scrollTop = document.getElementById("TestSL").scrollTop;
        //use scrollTop here
    }
    
    <SearchListWrapper id="TestSL" onScroll={this.handleScrollPosition} >
    

    【讨论】:

    • 这是 JavaScript 而非 React 的解决方案。 +您正尝试在 className 上使用 .getElementById
    • 也添加了带有 id="TestSL" 的 jsx
    猜你喜欢
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多