小编典典

如何在单击时切换仅一个元素的类

reactjs

我正在尝试在React中制作一组翻转卡片。您可以在下面看到我的代码。当我单击卡片时,它们全部翻转了,但是我的目标是仅翻转我单击的那些卡片。我怎样才能做到这一点?

这是我的卡组件:

import React from 'react';

export default class Card extends React.Component {
    render() {
        let className = this.props.condition ? 'card-component flipped' : 'card-component';
        return (
            <div onClick={this.props.handleClick} className={className}>
                <div className="front">
                    <img src={this.props.image} alt="card"/>
                </div>
                <div className="back">
                </div>
            </div>);
    }
}

这是我的Deck组件:

import React from 'react';
import Card from './Card.js';

const cardlist = require('../cardlist').cardlist;

export default class Deck extends React.Component{
    constructor(props) {
        super(props);
        this.state = {flipped: false};
    }
    handleClick() {
        this.setState({flipped: !this.state.flipped});
    }
    render() {
        const list = this.props.cards.map((card, index) => {
            return <Card
                         key={index}
                         handleClick={this.handleClick.bind(this)}
                         condition={this.state.flipped}
                         image={cardlist[card].path}
                    />});
        return(
            <ul>
                {list}
            </ul>)
    }
};

谢谢!


阅读 197

收藏
2020-07-22

共1个答案

小编典典

您可以使用索引。

export default class Deck extends React.Component{
    constructor(props) {
        super(props);

        //flipped true nonflipped false
        this.state = {
         flipStatus : props.cards.map((element) => false)
        }
    handleClick(index) {

        const newflipStatus = [...this.state.flipStatus]
        newflipStatus[index] = !this.state.flipStatus[index]
        this.setState({flipStatus: newflipStatus);
    }
    render() {
        const list = this.props.cards.map((card, index) => {
            return <Card
                         key={index}
                         handleClick={this.handleClick.bind(this)}
                         condition={this.state.flipped}
                         index={index}
                         image={cardlist[card].path}
                         flipped=this.state.flipStatus[index]

                    />});
        return(
            <ul>
                {list}
            </ul>)
    }
};

这是您的卡组件

export default class Card extends React.Component {
    render() {
        let className = this.props.condition ? 'card-component flipped' : 'card-component';
        return (
            <div onClick={() => this.props.handleClick(this.props.index)} className={className}>
                {!flipped && <div className="front">
                    <img src={this.props.image} alt="card"/>
                </div>}
                {flipped && <div className="back">
                </div>}
            </div>);
    }
}
2020-07-22