按顺序闪烁元素

时间:2018-04-17 04:44:05

标签: javascript arrays reactjs settimeout setinterval

美好的一天,所有,所以我做了这个我有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.forEach((item, i) => {
      setTimeout(() => {    
        pieces[i].classList.toggle(`${this.state.colors[i]}`);
      }, i * 500); // we're passing x
      setTimeout(() => {
        pieces[i].classList.toggle(`${this.state.colors[i]}`);
      }, 700 * (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'));

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

  • 基于递归创建循环机制。
  • 接受将启动下一个调用的回调,并根据条件在循环内调用它。

以下是动画功能。它会添加类并在指定时间后将其删除。

如果可用,它还会调用回调。所以调用者的职责是在终止时不要回调。

import re
from prettytable import PrettyTable
with open('testfile.txt','r') as input:
    table = PrettyTable(['Hostname', 'Version'])
    space = ''
    cntr = 1
    for line in input.read().split('\n'):
    match1=re.match(r'Hostname(.*)''|''version(.*)',line,
    re.MULTILINE)
       if match1:
          space = ''
          cntr += 1
          str= (match1.group())

          table.add_row([match1.group(1),match1.group(2)])
          print(table)
       else:
          cntr+=1
          space=space+'\n'+line

一个简单的基于递归的循环,如果元素和颜色存在则调用自身。您可以根据您的要求更新条件。

animate(element, className, callback) {
  setTimeout(() => {
    element.classList.toggle(className);
    setTimeout(() => {
      element.classList.toggle(className);
      if (callback) callback();
    }, 200)
  }, 500); // we're passing x
}

<强> Updated codepen

答案 1 :(得分:0)

这是一个有趣的事情要解决。以下是React setState和JS setTimeouts的一些帮助。

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

    this.state = {
      colors: ["yellow", "red", "blue", "green"],
      quantity: 3,
      output: [],
      currentIndex: -1
    };
  }
  getRandomInt() {
    return Math.floor(Math.random() * Math.floor(4));
  }
  generateNumbers() {
    const output = [];
    while (output.length !== 3) {
      const generatedNumber = this.getRandomInt();
      if (!output.includes(generatedNumber)) {
        output.push(generatedNumber);
      }
    }

    return output;
  }

  start() {
    const output = this.generateNumbers();
    this.setState({ output: output }, () => {
      output.forEach((item, index) => {
        setTimeout(() => {
          this.setState({ currentIndex: item });
        }, index * 1000);
      });
    });
  }
  render() {
    return (
      <div className="memory-game">
        {this.state.colors.map((gamePiece, i) => {
          let customClass = "";
          if (i === this.state.currentIndex) {
            const css = this.state.colors[this.state.currentIndex]
              ? this.state.colors[this.state.currentIndex]
              : "";
            if (css) {
              customClass = `blink-${css}`;
            }
          }
          return (
            <div
              key={`gamePiece-${i}`}
              className={`game-piece ${customClass}`}
            />
          );
        })}

        <button onClick={this.start.bind(this)} className="start-game">
          Start the game
        </button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
&#13;
html,
body {
  width: 100%;
  height: 100%;
}

#app {
  width: 100%;
  height: 100%;
  display: table;
  background: lightgoldenrodyellow;
}

.memory-game {
  width: 40%;
  margin: 100px auto;
}

.game-piece {
  width: 50%;
  height: 40px;
  display: inline-block;
  border-radius: 10px;
  margin-bottom: 10px;
  background-color: lightgray;
  &:nth-child(2n + 1) {
    margin-right: 10px;
  }
}

.start-game {
  margin: 0 auto;
  background: red;
  color: white;
  border: none;
  display: block;
  padding: 10px 15px;
  border-radius: 5px;
}

@-webkit-keyframes blinker-red {
  0% {
    opacity: 0;
    background-color: red;
  }
  50%{
  opacity:1;
  }
  100%{
    opacity: 0;
  }
}

@-webkit-keyframes blinker-yellow {
 0% {
    opacity: 0;
    background-color: yellow;
  }
  50%{
  opacity:1;
  }
  100%{
    opacity: 0;
  }
}

@-webkit-keyframes blinker-green {
   0% {
    opacity: 0;
    background-color: green;
  }
  50%{
  opacity:1;
  }
  100%{
    opacity: 0;
  }
}

@-webkit-keyframes blinker-blue {
   0% {
    opacity: 0;
    background-color: blue;
  }
  50%{
  opacity:1;
  }
  100%{
    opacity: 0;
  }
}

.blink-red {
  text-decoration: blink;
  animation-name: blinker-red;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
}

.blink-green {
  text-decoration: blink;
  animation-name: blinker-green;
  animation-duration: 1s;
}

.blink-blue {
  text-decoration: blink;
  animation-name: blinker-blue;
  animation-duration: 1s;
}

.blink-yellow {
  text-decoration: blink;
  animation-name: blinker-yellow;
  animation-duration: 1s;
}

.blink-red {
  text-decoration: blink;
  animation-name: blinker-red;
  animation-duration: 1s;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;