【发布时间】:2020-05-20 20:59:42
【问题描述】:
我的 React 代码如下。我从 FontAwesome 导入了 6 个骰子图标,目标是让它们像骰子一样旋转并改变数字。单击时,我转到 diceRoll 函数,该函数让我获得随机旋转总数、速度数(秒)和骰子选择。我也在尝试获取旋转和速度数字来动态调整旋转 css 动画的样式。我还想使用其他 setTimeout 函数来更改数字,就像滚动时发生的那样。
import React, { Component } from 'react';
import './style.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDiceOne, faDiceTwo, faDiceThree, faDiceFour, faDiceFive, faDiceSix } from '@fortawesome/free-solid-svg-icons';
export default class ExNav extends Component {
constructor(props) {
super(props);
this.state = {
dice: faDiceOne,
speed: 0,
spin: 0,
roll: '{animation: spin 0s ease 0}'
}
this.diceMove = this.diceMove.bind(this);
this.diceSet = this.diceSet.bind(this);
this.diceRoll = this.diceRoll.bind(this);
}
randNum() {
return Math.floor(Math.random()*6);
}
diceOptions() {
return [faDiceOne, faDiceTwo, faDiceThree, faDiceFour, faDiceFive, faDiceSix];
}
diceMove(speed, spin) {
this.setState({
roll: `{animation: spin ${speed}s ease ${spin}}`
})
setTimeout(
this.setState({
roll: '{animation: spin 0s ease 0}'
}), this.state.speed * 1000
)
}
diceSpeed() {
return Math.random()*1.5;
}
diceSpin() {
return Math.floor(Math.random()*3) + 1;
}
diceRoll() {
const diceNumOne = this.randNum();
const diceNumTwo = this.randNum();
const speed = this.diceSpeed();
const spin = this.diceSpin();
const dice = this.diceOptions();
this.setState({
speed,
spin
});
this.diceMove(this.state.speed, this.state.spin)
setTimeout(
this.setState({
dice: dice[diceNumOne]
}), this.state.speed*500
);
setTimeout(
this.setState({
dice: dice[diceNumTwo]
}), this.state.speed*1000 + 250
);
}
diceSet() {
const diceNum = this.randNum();
const dice = this.diceOptions();
this.setState({
dice: dice[diceNum]
})
}
componentDidMount() {
this.diceSet();
}
render () {
return (
<FontAwesomeIcon
id="dice"
className="dice-roll text-purple nav-text"
icon={this.state.dice}
style={this.state.roll}
onClick={this.diceRoll}
/>
);
}
}
diceSet 有效,但 setTimeout 部分无效。
我的style.css代码如下:
.dice-spin {
animation: spin;
}
@keyframes spin {
0%{
transform: rotate(0deg);
}
25% {
transform: rotateZ(30deg);
}
50% {
transform: rotateZ(270deg);
}
75% {
transform: rotateZ(180deg);
}
100% {
transform: rotateZ(360deg);
}
}
结果我遇到了以下错误:
TypeError: Failed to set an indexed property on 'CSSStyleDeclaration': Index property setter is not supported.
有其他人解决过这个问题吗?
【问题讨论】:
标签: reactjs dynamic styles state