我想点击一个按钮,并用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;
发布于 2019-08-29 15:31:12
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"
}
);
}
}
https://stackoverflow.com/questions/57704964
复制相似问题