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

时间:2019-08-29 07:17:10

标签: javascript reactjs

我想单击按钮并使用Web动画库为元素设置动画,出于某种原因,我无法使用document.getElementById进行定位,而不会出错。

错误在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;

1 个答案:

答案 0 :(得分:2)

TypeScript允许type guards。如果您检查该值是否不为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"
      }
    );
  }
}