无法读取 scrollY 的值

Not been able to read the value of scrollY

我一直在尝试读取 scrollY 的值(chrome 版本 96.0.4664.45(正式版)(64 位))。但这似乎不起作用。这是我的代码:

import React from "react";

import{useEffect, useState} from "react"


 
export default function Test() {
  const [offset, setOffset] = useState(0);
  const setScroll = () => {
    setOffset(window.scrollY);
  };

    useEffect(() => {
    window.addEventListener("scroll", setScroll);
    return () => {
      window.removeEventListener("scroll", setScroll);
    };
  }, []);

  return (
    <div className="App" style={{ height: "1000px" }}>
      <h1>Hello CodeSandbox</h1>
      <div>{offset}</div>
      
    </div>
  );
}

这是输出的图片:

这是您在问题中提供的代码片段(有效)。我只是将 scroll 事件目标从 window 更改为 document。请参阅文档滚动事件的 MDN 页面:https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">

const {useEffect, useState} = React;

function Test () {
  const [offset, setOffset] = useState(0);
  const setScroll = () => setOffset(window.scrollY);

  useEffect(() => {
    document.addEventListener("scroll", setScroll);
    return () => document.removeEventListener("scroll", setScroll);
  }, []);

  return (
    <div style={{ height: "1000px" }}>
      <h1>Hello CodeSandbox</h1>
      <div style={{ position: 'sticky', top: '1rem' }}>{offset}</div>
    </div>
  );
}

ReactDOM.render(<Test />, document.getElementById('root'));

</script>