gpt4 book ai didi

javascript - 如何在点击 react 时为唯一的一个元素切换类

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:39 25 4
gpt4 key购买 nike

我正在尝试在 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>)
}
};

谢谢!

最佳答案

您可以使用索引。

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>);
}
}

关于javascript - 如何在点击 react 时为唯一的一个元素切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com