4

正如你在我的例子中看到的

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

function App() {
  const items = ["this", "that", "those", "them", "these", "thisins"];

  const messagesRef = React.useRef(null);
  const scrollToBottom = () => {
    messagesRef.current.scrollIntoView({
      behavior: "smooth"
    });
  };

  React.useEffect(() => {
    if (messagesRef.current) {
      scrollToBottom();
    }
  }, [messagesRef]);

  return (
    // Page is overflowing, set height to mimic a full page
    <div className="App" style={{ marginTop: 70, height: 800 }}>
      {/* now set this div to overflow scroll with a small height */}
      <div style={{ overflowY: "scroll", height: 200, border: "solid" }}>
        {items.map(elem => (
          <div style={{ border: "solid", borderColor: "green", padding: 20 }}>
            {elem}
          </div>
        ))}
        {/* Set last element within this div to be the ref to scroll to */}
        <div ref={messagesRef} />
      </div>
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

页面加载,页面和嵌套滚动 div 都自动滚动。

我想要做的只是scrollIntoView我设置为我的参考的溢出 div。

我的目标是 ref,它正在工作,但我如何不滚动父元素呢?

4

1 回答 1

11

尝试这个:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });
于 2020-02-18T21:30:58.453 回答