0

我通过https://usehooks.com上的一段代码遇到了这行代码,

document.querySelector('body').current

我根本无法.current在规范中找到。我希望有人能在这种情况下澄清它的目的。

IntersectionObserver在完整示例中的 API 中使用(如下) - 也许 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;
}
4

2 回答 2

0

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");

于 2018-11-09T04:15:29.083 回答
0

很抱歉让您失望了,但它什么也没做。这只是提供undefinedIntersectionObserverAPI 的一种方式。如果您完全替换document.querySelector('body').currentundefined删除整个root字段,您仍然会得到相同的结果。

我删除了该字段以对其进行测试以验证相同的行为。在此处的 Codesandbox 链接中亲自尝试。

正如对示例的此评论所见,它可以完全删除:

您可以完全删除根,因为它默认为视口(也是 document.querySelector('body').current 始终未定义,可能是 document.body 但无论如何都不需要)

于 2018-11-09T06:01:59.453 回答