javascript - Typescript 中的 Intersection Observer 在 useRef 中抛出错误

标签 javascript css reactjs typescript intersection-observer

我在这里有一个完美的文本动画。我现在要添加的是 Intersection Observer,这样动画只有在我向下滚动到 Box 时才会开始。
所以我为实现这一目标所做的是:
我使用了 react Hook useRef用作我要观察的元素的引用,并将其应用到我的 Box 中,ref={containerRef} .然后声明了一个回调函数,它接收一个 IntersectionObserverEntries 数组作为参数,在这个函数中,我采用第一个也是唯一一个条目并检查它是否与视口(viewport)相交,如果是,那么它调用 setIsVisible 并使用 entry.isIntersecting (真假)。之后,我添加了 react 钩子(Hook) useEffect 并使用回调函数和我之前创建的选项创建了一个观察者构造函数。我在一个名为 useElementOnscreen 的新钩子(Hook)中实现了逻辑
但是 Typescript 在 containerRef?.current 处告诉我一个错误:

Argument of type 'IntersectionObserver' is not assignable to parameter of type 'Element'.
  Type 'IntersectionObserver' is missing the following properties from type 'Element': attributes, classList, className, clientHeight, and 160 more.
而且我不确定如何解决这个错误。我想这也是我的ref={containerRef}也在抛出错误
The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; component?: ElementType<...> | undefined; ref?: Ref<...> | undefined; sx?: SxProps<...> | undefined; } & CommonProps & Omit<...>'
动画:
因此,TopAnimateBlock 和 BottomAnimateBlock 具有 numOfLine 属性,因此 block 内有多少行。 BottomAnimateBlock 中的第二个属性是 delayTopLine,它应该与 TopAnimateBlock 中的 numOfLine 具有相同的数字,因为我们需要等待顶行播放。TextAnimation.tsx
import { Box, Stack, Typography } from '@mui/material';
import React, { useRef, useEffect, useState } from 'react';
import styled, { keyframes } from 'styled-components';

const showTopText = keyframes`
  0% { transform: translate3d(0, 100% , 0); }
  40%, 60% { transform: translate3d(0, 50%, 0); }
  100% { transform: translate3d(0, 0, 0); }
`;
const showBottomText = keyframes`
  0% { transform: translate3d(0, -100%, 0); }
  100% { transform: translate3d(0, 0, 0); }
`;

const Section = styled.section`
  width: calc(100% + 10vmin);
  display: flex;
  flex-flow: column;
  padding: 2vmin 0;
  overflow: hidden;
  &:last-child {
    border-top: 1vmin solid white;
  }
`;

const Block = styled.div<{ numOfLine: number }>`
  position: relative;
`;
const TopAnimateBlock = styled(Block)`
  animation: ${showTopText} calc(0.5s * ${props => props.numOfLine}) forwards;
  animation-delay: 0.5s;
  transform: translateY(calc(100% * ${props => props.numOfLine}));
`;
const BottomAnimateBlock = styled(Block)<{ delayTopLine: number }>`
  animation: ${showBottomText} calc(0.5s * ${props => props.numOfLine}) forwards;
  animation-delay: calc(0.7s * ${props => props.delayTopLine});
  transform: translateY(calc(-100% * ${props => props.numOfLine}));
`;

const TextStyle = styled.p<{ color: string }>`
  font-family: Roboto, Arial, sans-serif;
  font-size: 12vmin;
  color: ${props => props.color};
`;


const useElementOnScreen = (options) => {
    const containerRef = useRef<IntersectionObserver | null>(null);
    const [isVisible, setIsVisible] = useState(false);

    const callbackFunction = (entries) => {
        const [entry] = entries;
        setIsVisible(entry.isIntersecting);
    };

    useEffect(() => {
        const observer = new IntersectionObserver(callbackFunction, options);

        if (containerRef.current) observer.observe(containerRef?.current);

        return () => {
            if (containerRef.current) observer.unobserve(containerRef?.current);
        };
    }, [containerRef, options]);

    return [containerRef, isVisible];
};

export function Details() {
    const [containerRef, isVisible] = useElementOnScreen({
        root: null,
        rootMargin: '0px',
        threshold: 1.0,
    });

    return (
    <>
    <Typography>Scroll Down</Typography>
     <Box ref={containerRef}>
      <Section>
        <TopAnimateBlock numOfLine={2}>
          <TextStyle color="grey">mimicking</TextStyle>
          <TextStyle color="white">apple's design</TextStyle>
        </TopAnimateBlock>
      </Section>
      <Section>
        <BottomAnimateBlock numOfLine={1} delayTopLine={2}>
          <TextStyle color="white">for the win!</TextStyle>
        </BottomAnimateBlock>
      </Section>
    </Box>
</>
  );
};

最佳答案

我可以在代码中大致找到 2 个问题:
首先是这个声明:

 const containerRef = useRef<IntersectionObserver | null>(null);
通用 useRef 的实现正在处理 IntersectionObserver | null .这表明 ref 容器将保存 IntersectionObserver 的实例。或 null .但取而代之的是 refBox 一起使用元素,(对于那些不熟悉 material-UI 的人,这将类似于 div )。
此语句可以更改为:
  const containerRef = useRef<HTMLDivElement | null>(null);
其次,未声明 Hook 的返回类型,TS auto 通过查看返回的内容([containerRef, isVisible])将其检测为数组。 Typescript 推断的类型变为:
Typescript return type for the hook(boolean | React.MutableRefObject<HTMLDivElement | null>)[] .这意味着返回类型是一个元素数组,每个元素都可以具有上述 3 种类型之一。
由于类型实际上是 tuple并且两个返回的数组元素都是不同的类型(我们事先知道),推断的类型不正确并且 TS 提示。
明确声明 这在定义钩子(Hook)时会阻止 Typescript 提示。
const useOnScreen = <T,>(options : T): [MutableRefObject<HTMLDivElement | null>, boolean] => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [isVisible, setIsVisible] = useState(false);

  const callbackFunction = (entries : : IntersectionObserverEntry[]) => {
    const [entry] = entries;
    setIsVisible(entry.isIntersecting);
  };

  useEffect(() => {
    const observer = new IntersectionObserver(callbackFunction, options);

    if (containerRef.current) observer.observe(containerRef?.current);

    return () => {
      if (containerRef.current) observer.unobserve(containerRef?.current);
    };
  }, [containerRef, options]);

  return [containerRef, isVisible];
};
一个 link解释元组返回类型和数组返回类型之间的区别。

关于javascript - Typescript 中的 Intersection Observer 在 useRef 中抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73051303/

相关文章:

javascript - 动态添加跨度后如何自动适应输入字段?

javascript - -js-React "component did mount"示例

reactjs - react 无效的钩子(Hook)调用错误和故事书6

javascript - 对象数组的 lodash 总和

javascript - Angular HTTP 'get' 请求 304 错误

html - 在 CSS 中将子级菜单放置在其父级旁边

reactjs - 在 ReactJS 中获取表单数据

javascript - 单击事件未在 div 元素上注册 (jQuery/HTML/CSS)

javascript - 从 html5 应用程序打开 pdf 的外部链接 - PhoneGap

javascript - 如何读取本地文本文件?