Реагируйте: [useRef, scrollIntoView,] Как автоматически прокрутить указанный c div внутри переполняющейся страницы? - PullRequest
0 голосов
/ 19 февраля 2020

Как вы можете видеть в моем примере

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, который я установил в качестве ссылки.

Я нацеливаю ссылку, и она работает, но как мне НЕ прокручивать родительский элемент?

1 Ответ

1 голос
/ 19 февраля 2020

Попробуйте это:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });
...