简体   繁体   English

React TypeScript Web Animations API-对象可能为“空”

[英]React TypeScript Web Animations API - Object is possibly 'null'

I want to click a button and animate an element with the web animation library, For some reason I cant target with document.getElementById without getting an error. 我想单击一个按钮并使用Web动画库对元素进行动画处理,由于某种原因,我无法使用document.getElementById进行定位,而不会出现错误。

The error is on document.getElementById and is Object is possibly 'null'.ts(2531) 错误发生在document.getElementById ,并且Object is possibly 'null'.ts(2531)

import React, {useContext} from "react";

const Home: React.FC = () => {

  function startAnimation() {
    var player = document.getElementById('home').animate([
      { transform: 'scale(1)', opacity: 1, offset: 0 },
      { transform: 'scale(.5)', opacity: .5, offset: .3 },
      { transform: 'scale(.667)', opacity: .667, offset: .7875 },
      { transform: 'scale(.6)', opacity: .6, offset: 1 }
    ], {
      duration: 700, 
      easing: 'ease-in-out', 
      delay: 10, 
      iterations: Infinity, 
      direction: 'alternate', 
      fill: 'forwards',
    });
  }

  return (

  <nav onClick={startAnimation}>
     Click Me
  </nav>

  <main id="home">
    Animate me
  </main>

  );
}

export default Home;

TypeScript allows for type guards . TypeScript允许类型保护 If you check to see if the value is not null, then the error will not occur. 如果检查该值是否不为null,则不会发生该错误。

function startAnimation() {
  var player = document.getElementById("home");

  if (player !== null) {
    // This side of the if-statement will never execute if player is null

    player.animate(
      [
        { transform: "scale(1)", opacity: 1, offset: 0 },
        { transform: "scale(.5)", opacity: 0.5, offset: 0.3 },
        { transform: "scale(.667)", opacity: 0.667, offset: 0.7875 },
        { transform: "scale(.6)", opacity: 0.6, offset: 1 }
      ],
      {
        duration: 700,
        easing: "ease-in-out",
        delay: 10,
        iterations: Infinity,
        direction: "alternate",
        fill: "forwards"
      }
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM