React.js:按下按钮以随机化数组

时间:2019-05-15 06:31:32

标签: javascript reactjs button random

基本上,我正在尝试制作一个卡片程序,该程序将随机抽取52张卡片中的5张。这些卡不得重复。我已经通过传统的javascript找出了随机器。但是,我正在使用ReactJs创建一个按钮,如果按下该按钮,将创建一组新的五张卡。

class Reset extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }

  handleClick() {...}

  render() {
    return <button onClick={this.handleClick}>{...}</button>;
  }
}

const cards = [
  "A♥",
  "A♠",
  "A♦",
  "A♣",
  "2♣",
  "3♣",
  "4♣",
  "5♣",
  "6♣",
  "7♣",
  "8♣",
  "9♣",
  "10♣",
  "K♣",
  "Q♣",
  "J♣",
  "2♦",
  "3♦",
  "4♦",
  "5♦",
  "6♦",
  "7♦",
  "8♦",
  "9♦",
  "10♦",
  "K♦",
  "Q♦",
  "J♦",
  "2♥",
  "3♥",
  "4♥",
  "5♥",
  "6♥",
  "7♥",
  "8♥",
  "9♥",
  "10♥",
  "K♥",
  "Q♥",
  "J♥",
  "2♠",
  "3♠",
  "4♠",
  "5♠",
  "6♠",
  "7♠",
  "8♠",
  "9♠",
  "10♠",
  "K♠",
  "Q♠",
  "J♠"
];
var hand = [];

function in_array(array, el) {
  for (var i = 0; i < array.length; i++) if (array[i] == el) return true;
  return false;
}

function get_rand(array) {
  var rand = array[Math.floor(Math.random() * array.length)];
  if (!in_array(hand, rand)) {
    hand.push(rand);
    return rand;
  }
  return get_rand(array);
}

for (var i = 0; i < 5; i++) {
  document.write(get_rand(cards));
}

ReactDOM.render(<Reset />, document.getElementById("root"));

基本上,为了使代码重新随机化包,我必须在部分中添加“ ...”。

2 个答案:

答案 0 :(得分:1)

尝试类似的方法,我保留了您已经编写的代码。您实际上只需要将该逻辑移到处理程序中即可。

这也是沙盒:https://codesandbox.io/s/yv93w19pkz

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor(props) {
      super(props);
      this.state = { 
        cards: ["A♥", "A♠", "A♦", "A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "K♣", "Q♣", "J♣", "2♦", "3♦", "4♦", "5♦", "6♦", "7♦", "8♦", "9♦", "10♦", "K♦", "Q♦", "J♦", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥", "10♥", "K♥", "Q♥", "J♥", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "K♠", "Q♠", "J♠"],
        hand: [] 
      }

       this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    const cards = this.state.cards

    const newHand = []

    function get_rand(array) {
       var rand = array[Math.floor(Math.random() * array.length)];
       if (!newHand.includes(rand)) {
          newHand.push(rand);
       } else {
         get_rand(cards);
       }
     }

    for (var i = 0; i < 5; i++) {
       get_rand(cards);
    }

    this.setState({
      hand: newHand
    })

  }

  render() {
    const { hand } = this.state
      return (
        <div>
          { hand ? (hand.map((card) => {
            return <p>{card}</p>
           })) : (
            null
          )}
          <button onClick={this.handleClick}>Randomize
          </button>
        </div>
      );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

答案 1 :(得分:0)

尝试声明卡的状态并在单击时更新

Try to declare the cards in the state and update when you click on it