【问题标题】:Why do I get an error TS2339: Property 'classList' does not exist on type 'never'?为什么我会收到错误 TS2339:“从不”类型上不存在属性“classList”?
【发布时间】:2019-10-17 23:13:10
【问题描述】:

我正在开发一个简单的组件“BackToTop”

const BackToTop: React.FC = () => {
  const bttEl = useRef(null);
  function scrollHandler(): void { 
    var bttHtmlEl: HTMLElement | null = bttEl.current;
    // console.log(bttHtmlEl); Element OK!
    if ( bttHtmlEl ) {
      window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
    } else {
      console.error('BackToTop is null.');
    }
  }
  useEffect( ()=>{
    window.addEventListener('scroll', scrollHandler);
      return ()=>{
        window.removeEventListener('scroll', scrollHandler);
      }        
    }
  )

src/components/BackToTop.tsx:54:43 - 错误 TS2339:“从不”类型上不存在属性“classList”。

54 window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide'); ~~~~~~~~~

src/components/BackToTop.tsx:54:82 - 错误 TS2339:“从不”类型上不存在属性“classList”。

54 window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide'); ~~~~~~~~~

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    TypeScript 告诉您 if 语句中的代码块将 never 运行。

    const bttEl = useRef(null);
    function scrollHandler(): void { 
      var bttHtmlEl: HTMLElement | null = bttEl.current;
      if (bttHtmlEl) {
        // According to the type definitions,
        // this code block will never execute,
        // because useRef(null).current is always null.
      }
    }
    

    该代码块将永远不会运行,因为useRef(null).current 将始终返回null

    useRef 返回一个可变 ref 对象,其 .current 属性初始化为传递的参数 (initialValue)。

    换句话说,TypeScript 是这样解释你的代码的:

    var bttHtmlEl = null;
    if (bttHtmlEl) {
      // This code block will never execute.
    }
    

    由于代码块永远不会执行,因此该代码块内的任何变量都将never 有一个值。这就是the never type represents

    【讨论】:

    • 感谢您的帮助。问题是在 js 上这段代码有效......我使用官方文档中的 useRef 示例你当然可以这样做 const any = document.createElement('div');常量 bttEl = useRef(任何东西); ,但是……在这种情况下怎么办——为了以后和毕竟写在JS上的任何有效代码都是编译TS
    【解决方案2】:

    问题的解决方法

    const bttEl = useRef<HTMLElement>(null);
    

    【讨论】:

      【解决方案3】:

      useRef 启动时为空,使用前需要检查节点是否存在。

      const anyRefName = useRef<HTMLDivElement>(null);
      
      const doStuff = () => {
          const divNode = anyRefName.current;
          divNode !== null && divNode.classList.add("my-class-name");
      }
      
      <div ref={anyRefName}>
      ...
      </div>
      

      【讨论】:

        猜你喜欢
        • 2019-06-06
        • 2020-06-27
        • 1970-01-01
        • 1970-01-01
        • 2022-12-13
        • 2021-06-21
        • 1970-01-01
        • 2021-01-22
        • 2019-01-21
        相关资源
        最近更新 更多