【问题标题】:Typescript error when importing Intersection Observer导入 Intersection Observer 时出现打字稿错误
【发布时间】:2021-08-14 17:46:25
【问题描述】:

我将使用Intersection Observer API 在我的 React 应用程序中创建一个无限滚动。

但是,在将 Intersection Observer 导入 React 组件时,我收到一条警告消息 Could not find a declaration file for module 'intersection-observer'. '/Users/rutakalytyte/Desktop/mano/reactprojects/react-movies-app/node_modules/intersection-observer/intersection-observer.js' implicitly has an 'any' type. Try `npm i --save-dev @types/intersection-observer` if it exists or add a new declaration (.d.ts) file containing `declare module 'intersection-observer';`

这是代码

import{ useContext, useRef, useEffect } from "react";
import '../../App.scss';
import 'intersection-observer';
import 'intersection-observer/intersection-observer.js'

const posterBaseUrl = "https://image.tmdb.org/t/p/w300";

const CatalogCards = () =>  { 
  const { setSelectedMovie, setIsMoviePageFirstTimeOpened } = useContext(MoviesContext);
  const loadingRef = useRef<HTMLDivElement|null>(null);
  
  const isBottomVisible = useIntersectionObserver(
    loadingRef,
    {
      threshold: 0 // to trigger event as soon as the element is in the viewport
    },
    false // to not remove the observer after intersected
  );

  useEffect(() => {
    //load next page when bottom is visible
    isBottomVisible && console.log("BOTTOM REACHED");
  }, [isBottomVisible]);

  return (
    <div >
      <div>Some components here</div>
      <div ref={loadingRef}>...</div>
    </div>
  );
}

export default CatalogCards;

这些是我得到的错误:

这是我的package.json

另外,运行 npm i --save-dev @types/intersection-observer 命令我得到“代码 E404 npm 错误! 404 未找到 - 获取 https://registry.npmjs.org/@types%2fintersection-observer"

我该如何解决?谢谢!

【问题讨论】:

标签: javascript reactjs typescript react-hooks intersection-observer


【解决方案1】:

您可以在项目文件夹的根目录中添加一个index.d.ts 文件并将这一行放入其中:declare module "intersection-observer"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2018-03-19
    • 2020-09-19
    • 2017-05-29
    • 2019-08-23
    相关资源
    最近更新 更多