简体   繁体   English

如何在反应组件中使用一个类的方法?

[英]How to use one class's method in react component?

I'm creating a poker game and I have a Card deck class which has methods getDeck, getCard and getCards(howMany) and a Card component.我正在创建一个扑克游戏,我有一个卡片组类,它具有方法 getDeck、getCard 和 getCards(howMany) 以及一个 Card 组件。 I need to use CardDeck's method in App, because I need to save the deck in state to splice already used cards and generate new deck after 52 cards are used.我需要在App中使用CardDeck的方法,因为我需要在状态下保存一副牌,把已经用过的牌拼接起来,用完52张牌后生成新的一副牌。 I've got a button that generates new 5 cards (a hand) and I need another one to generate new deck.我有一个按钮可以生成新的 5 张牌(一手牌),我需要另一个按钮来生成新的牌组。

this is my app.js这是我的 app.js

class App extends Component {
  constructor() {
    super();
    this.state = {
      display: false,
      cards: CardDeck.getCards(5)
    }
  }
  displayDeck = () => {
    this.setState({display: true});
  }
  render() {
    return (
      <div>
        <button className='btn' onClick={this.displayDeck}>Button</button>
        {this.state.display ?
           <div className="App playingCards fourColours faceImages">
           <Card rank={this.state.cards[0].rank} suit={this.state.cards[0].suit} />
           <Card rank={this.state.cards[1].rank} suit={this.state.cards[1].suit} />
           <Card rank={this.state.cards[2].rank} suit={this.state.cards[2].suit} />
           <Card rank={this.state.cards[3].rank} suit={this.state.cards[3].suit} />
           <Card rank={this.state.cards[4].rank} suit={this.state.cards[4].suit} />
         </div> :
           null
        }
      </div>
    );
  }
  }

this is my CardDeck class:这是我的 CardDeck 类:

let getRandomInt = (min, max) => {    
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
class CardDeck {
    constructor () {
        this.deck = this.getDeck();
    }
    getDeck = () => {
        const suits = ['hearts', 'diams', 'clubs', 'spades'];
        const ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'];
        let currentDeck = [];
        for (let suit of suits) {
            for (let rank of ranks) {
                let card = {suit: suit, rank: rank};
                currentDeck.push(card);
            }
        }
        return currentDeck;
    }
    getCard = () => {
        let min = 0;
        let max = 52;
        let card;
        while (card === undefined) {
            let number = getRandomInt(min, max);
            card = this.deck[number];
            this.deck.splice(number, 1);
        }
        return card;
    }
    getCards = howMany => {
        let cardsArray = [];
        for (let i=0; i < howMany; i++) {
            let card = this.getCard();
            cardsArray.push(card);
        }
        return cardsArray;
    }

}

my Card component:我的卡组件:

class Card extends Component {
    render(props) {
        const suits = {
            diams: '♦',
            hearts: '♥',
            clubs: '♣',
            spades: '♠'
        };
        const ranks = {
            'q': 'Q',
            'j': 'J',
            'k': 'K',
            'a': 'A',
            '2': '2',
            '3': '3',
            '4': '4',
            '5': '5',
            '6': '6',
            '7': '7',
            '8': '8',
            '9': '9',
            '10': '10'
        }
        var  classNames = "card " +  "rank-" + this.props.rank + " " + this.props.suit;
        return (
            <div className={classNames}>
                <span className="rank">{ranks[this.props.rank]}</span>
                <span className="suit">{suits[this.props.suit]}</span>
            </div>
        );
    }
}

Thanks in advance.提前致谢。

since you are using a class , you need to take instance of the class.由于您使用的是类,因此您需要获取类的实例。

so replace with the below snippet.所以用下面的代码片段替换。 I hope this will solve the issue我希望这能解决问题

//App.js
    constructor() {
        super();
        let carDeck = new CardDeck()
        this.state = {
          display: false,
          cards: carDeck.getCards(5)
        }
      }

The issue I see here is you are not making an instance of the class you are trying to access the method for.我在这里看到的问题是您没有创建您尝试访问其方法的类的实例。 CardDeck is another class, to use it's method usually you need to make a new instance of CardDeck like DILEEP THOMAS has written in his answer. CardDeck是另一个类,通常你需要做的新实例,使用它的方法CardDeck像迪利普·托马斯写在他的回答。

If you don't want to instantiate a new CardDeck() then make your getCards method static like so: static getCards = howMany => { // code } .如果你不希望实例化一个new CardDeck()然后让你的getCards方法static像这样: static getCards = howMany => { // code } This way you can access this method outside of it's class without creating a new instance of that class.通过这种方式,您可以在类之外访问此方法,而无需创建该类的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM