闪烁元素

时间:2018-04-16 22:43:06

标签: javascript jquery reactjs intervals

美好的一天,所有,所以我做了这个我有4个方格的东西,当我点击一个按钮时,3个随机方块必须按顺序闪烁不同的颜色。我需要存储在数组中闪烁的方块的id。我无法弄清楚的是如何让它们一个接一个地眨眼。这就是我到目前为止...... https://codepen.io/anon/pen/dmBxYe?editors=0110

class App extends React.Component {
constructor() {
    super();

    this.state = {
        colors: ['yellow', 'red', 'blue', 'green'],
        quantity: 3,
    }
}
start() {
    const {quantity} = this.state;
    const quantityArray = Array.from(Array(quantity));
    const pieces = Array.from(document.querySelectorAll('.game-piece'));

    quantityArray.map((item, i) => {
        setTimeout(() => {
            pieces[i].classList.toggle(`${this.state.colors[i]}`)
        }, 1000);
      pieces[i].classList.toggle(`${this.state.colors[i]}`);
    });
}
render() {
    return (
        <div className="memory-game">
            {this.state.colors.map((gamePiece, i) => {
                return <div key={`gamePiece-${i}`} className="game-piece"></div>
            })}

            <button onClick={this.start.bind(this)} className="start-game">Start the game</button>
        </div>
    )
}
}
React.render(<App />, document.getElementById('app'));

1 个答案:

答案 0 :(得分:0)

我不确定最后你想要它看起来是什么样子,但是在切换颜色时只需添加另一个setTimeout

quantityArray.forEach((item, i) => {
  setTimeout(() => {
    pieces[i].classList.toggle(`${this.state.colors[i]}`)
  }, 1000 * (i + 3));
  setTimeout(() => {
    pieces[i].classList.toggle(`${this.state.colors[i]}`);
  }, 1000 * (i))
});

https://codepen.io/anon/pen/wmVbdz?editors=0110

此外,除非您要映射到新数组,否则请使用forEach,而不是map