簡體   English   中英

從父 state 更改更新子組件道具值

[英]Update child component props values from parent state change

我有一個父組件,它在 state 更改時更新了子組件的值(來自 JSON 文件)。 我是 React 的新手。

子組件是一張“卡片”。 父母是一個“游戲板”,它從一副牌中取出卡片並將它們放在玩家手中。 子“卡片”組件用於渲染卡片(單擊時它也有一個翻轉 animation),它通過其道具獲取其“值”。 “手牌大小”(要顯示的牌數)也可以從另一個父母那里改變,我意識到這會產生同樣的問題,我還沒有走那么遠!

父“Game.js”:

import React, { Component } from 'react';
import './Game.css';
import Card from '../../components/Card/Card.js';
import cardsdata from '../../data/cards-data.json';

class Game extends Component {
    constructor(props) {
        super(props);

        this.state = {
            gamemode: props.mode,
            handsize: parseInt(props.size),
            hand: [],
            deck: cardsdata.slice()
        };
        this.refreshHand = this.refreshHand.bind(this)
    }

    componentDidMount() {
        this.refreshHand();
    }

    refreshHand() {
        // check if there is enough cards left in deck
        if (this.state.deck.length >= this.state.handsize) {
            // grab random cards to renew hand
            let newhand = Array(this.state.handsize).fill(null);
            let newdeck = this.state.deck.slice();
            for (let i = 0; i < this.state.handsize; i++) {
                let rng = Math.floor(Math.random() * newdeck.length);
                newhand[i] = newdeck.splice(rng, 1)[0];
            }

            this.setState({
                hand: newhand,
                deck: newdeck
            });
        }
    }
    
    render() {
        let handview = this.state.hand.map((card, index) => {
            return (
                <Card card={card} key={index} />
            );
        });

        return (
            <div className="Game-container">
                {handview}
                <button onClick={() => this.refreshHand()}>Refresh</button>
                <p>Cards left in deck: {this.state.deck.length}</p>
            </div>
        );
    }

}

export default Game;

孩子“Card.js”:

import React, { Component } from 'react';
import './Card.css';

class Card extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isFlipped: false,
            wrapperclass: "card_wrapper",
            index: props.index,
            shine: props.card.shine,
            rough: props.card.rough
        };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e) {
        e.preventDefault();

        if (this.state.isFlipped) {
            this.setState(prevState => ({
                isFlipped: false,
                wrapperclass: "card_wrapper anim_reverse"
            }));
        } else {
            this.setState(prevState => ({
                isFlipped: true,
                wrapperclass: "card_wrapper anim_forward"
            }));
        }
    }

    componentWillReceiveProps(newProps) {
        this.setState({
            index: newProps.index,
            shine: newProps.card.shine,
            rough: newProps.card.rough
        });
    }

    render() {
        return (
            <div className="card_box" >
                <div className={this.state.wrapperclass} onClick={this.handleClick}>
                    <div className="card_face">
                        <span className="align-center">{this.state.rough}</span>
                    </div>
                    <div className="card_face c_back">
                        <span className="align-center">{this.state.shine}</span>
                    </div>
                </div>
            </div>
        )
    }
}

export default Card;

由於我仍在大量學習所有這些,因此將不勝感激任何額外的反饋。

我在子組件中使用了“componentWillReceiveProps(newProps)”並且它可以工作,但我已經讀過它不應該再使用了。 我應該怎么做?

我找到了如何修復它。

用於呈現每個子組件的索引始終是基本數組索引(從 0 到“handsize”是什么)。

我在保存卡片值的 JSON 中添加了一個索引,因此每個值都有一個唯一的鍵。

所以渲染父級變成:

render() {
    let handview = this.state.hand.map((card, index) => {
        return (
            <Card card={card} key={card.index} />
        );
    });

    return (
        <div className="Game-container">
            {handview}
            <button onClick={() => this.refreshHand()}>Refresh</button>
            <p>Cards left in deck: {this.state.deck.length}</p>
        </div>
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM