【发布时间】:2021-11-06 13:14:23
【问题描述】:
我正在尝试制作一个漂浮的热气球风格按钮(在 x 和 y 空间上平移)。目前我正在使用 CSS 变量来设置动画属性,但我只能这样做一次,否则我会收到一条错误消息
“TypeError:无法分配给对象'#'的只读属性'--animation-time'”
我如何解决这个问题,以便能够为动画开始、结束和持续多长时间设置新的随机属性?
目前我有这个:
class HotAir extends React.Component{
constructor(props){
super(props);
this.state = {
link: props.link,
cls: props.cls,
img: props.img,
text: props.text,
}
}
render(){
var cssProperties = {};
cssProperties['--animation-time'] = Math.random()*10 + 's';
console.log(cssProperties);
return(
<div className="balloon" style={cssProperties} onAnimationEnd={()=> cssProperties['--animation-time'] = '60s'}>
<Link to={this.state.link}><button className="balloonbutt">
<img src={this.state.img} alt=""></img>
<div className="balloontext">{this.state.text}</div></button>
</Link>
</div>
);
}
}
这是我的相关css
.balloon{
--animation-time: 60s;
--x-float-start: 10vw;
--y-float-start: 10vh;
--x-float-end: 20vw;
--y-float-end: 20vh;
position: relative;
text-align: center;
color: white;
animation: float var(--animation-time) linear;
}
@keyframes float{
0%{
left: var(--x-float-start);
top: var(--y-float-start);
}
100%{
left: var(--x-float-end);
top: var(--y-float-end);
}
}
【问题讨论】:
-
我试过你的代码,在stackblitz.com/edit/react-ts-pemaug上没有问题
-
一个建议,不要使用 var。改用 const 或 let 。我认为这一定与您的代码 linting 设置有关。
-
@SanishJoseph 是的,当我在动画完成后尝试再次设置时会出现问题
-
我认为您应该将变量移动到状态对象并按照我的回答进行处理。如果您仍然遇到错误,请告诉我。
标签: javascript css reactjs animation