我想单击按钮并使用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;
答案 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"
}
);
}
}