На что ссылается свойство .current метода querySelector? - PullRequest
0 голосов
/ 09 ноября 2018

Я наткнулся на эту строку кода через фрагмент https://usehooks.com,

document.querySelector('body').current

Я не смог найти .current в спецификации вообще. Я надеялся, что кто-то сможет прояснить его назначение в этом контексте.

Он используется в API IntersectionObserver в полном примере (ниже) - возможно, API предоставляет свойство?

Любая помощь очень ценится. Заранее спасибо.


Ниже приводится полный исходный код:

import { useState, useEffect, useRef } from 'react';

// Usage
function App() {
  // Ref for the element that we want to detect whether on screen
  const ref = useRef();
  // Call the hook passing in ref and root margin
  // In this case it would only be considered onScreen if more ...
  // ... than 300px of element is visible.
  const onScreen = useOnScreen(ref, '-300px');

  return (
    <div>
      <div style={{ height: '100vh' }}>
        <h1>Scroll down to next section ?</h1>
      </div>
      <div
        ref={ref}
        style={{
          height: '100vh',
          backgroundColor: onScreen ? '#23cebd' : '#efefef'
        }}
      >
        {onScreen ? (
          <div>
            <h1>Hey I'm on the screen</h1>
            <img src="https://i.giphy.com/media/ASd0Ukj0y3qMM/giphy.gif" />
          </div>
        ) : (
          <h1>Scroll down 300px from the top of this section ?</h1>
        )}
      </div>
    </div>
  );
}

// Hook
function useOnScreen(ref, margin = '0px') {
  // State and setter for storing whether element is visible
  const [isIntersecting, setIntersecting] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        // Update our state when observer callback fires
        setIntersecting(entry.isIntersecting);
      },
      {
        rootMargin: margin,
        root: document.querySelector('body').current
      }
    );
    if (ref.current) {
      observer.observe(ref.current);
    }
    return () => {
      observer.unobserve(ref.current);
    };
  }, []); // Empty array ensures that effect is only run on mount and unmount

  return isIntersecting;
}

Ответы [ 2 ]

0 голосов
/ 09 ноября 2018

Извините, что разочаровал, но это ничего не делает. Это просто способ предоставления undefined API IntersectionObserver. Если вы замените document.querySelector('body').current на undefined или полностью удалите поле root, вы все равно получите тот же результат.

Я удалил это поле, чтобы проверить его на то же поведение. Попробуйте сами в Codesandbox по ссылке здесь .

Как видно из этого комментария к примеру, его можно полностью удалить:

Вы можете полностью удалить root, так как он все равно по умолчанию установлен в окне просмотра (также document.querySelector ('body'). Current всегда неопределен, может быть document.body, но в любом случае не нужен)

0 голосов
/ 09 ноября 2018

document.querySelector('body').current - это просто свойство элемента body, которое не имеет ничего общего с document.querySelector. Возможно, он был задан где-то еще, поскольку он не является существующим свойством элемента body.

var body = document.querySelector("body");
console.log("body.current:", "body.current");
body.current = "SOMEVALUE";
console.log("After setting body.current");
console.log("body.current:", "body.current");
...