我正在尝试在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>)
}
};谢谢!
发布于 2018-01-17 04:41:53
您可以使用索引。
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>);
}
}发布于 2018-01-17 04:36:47
在handleClick函数中,您将为整个牌组设置“翻转”状态变量,而不是为一张牌设置“翻转”状态变量,这就是为什么整个牌组一起更改。解决方案很简单,就是让每个卡片都有一个状态来指定它是否翻转,而不是在父级别上创建变量
https://stackoverflow.com/questions/48289315
复制相似问题