为什么会出现错误TS2339:类型“从不”上不存在属性“ classList”?

时间:2019-06-01 19:17:10

标签: reactjs typescript

我正在开发一个简单的组件“ 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');                                                                                     ~~~~~~~~~

2 个答案:

答案 0 :(得分:2)

TypeScript告诉您const booksFromUser = firestore.collection(`books`).where(`userId`, `==`, WHATEVER_USER_ID) const booksFromGroup = firestore.collection(`books`).where(`groupId`, `==`, WHATEVER_GROUP_ID) 语句中的代码块将运行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返回一个可变的ref对象,该对象的useRef属性被初始化为传递的参数(.current)。

换句话说,TypeScript正在这样解释您的代码:

initialValue

由于该代码块将永远不会执行,因此该代码块内的任何变量将var bttHtmlEl = null; if (bttHtmlEl) { // This code block will never execute. } 带有值。这就是the never type represents

答案 1 :(得分:0)

问题的解决方法

const bttEl = useRef<HTMLElement>(null);