因此,单击它只会将一张卡切换回来。因此,在我的函数中正确读取了切换,但我不明白为什么它没有将两张卡都翻转过来,它只会翻转我数组中位置 [1] 处的卡,而位置 [0] 仅在翻转卡片时不受影响翻转功能它翻转两张卡,但似乎当我设置数组时我遗漏了一些东西。另外,如果我尝试执行 cardChoiceId[0].setToggle(false) 之类的操作,我会收到一个类型错误,说不是函数,所以这不是解决方案,这里是代码
import bg from '../images/card-bg.png'
let cardChoiceId = []
let cardsWon = []
const GameCard = ({ img, name, num, setScore, setResult, cardArray }) => {
const [toggle, setToggle] = useState(false)
const checkForMatch = () => {
if (cardChoiceId[0] === cardChoiceId[1]) {
alert(`That's a Match`)
setToggle(true)
cardsWon.push(cardChoiceId)
cardChoiceId = []
setScore(+1)
if (cardsWon.length === cardArray.length) {
setResult(` Congratz!!! You Win `)
}
}
else {
setToggle(false)
cardChoiceId = []
}
}
const flip = () => {
setToggle(!false)
cardChoiceId.push(name)
console.log(cardChoiceId)
if (cardChoiceId.length === 2) {
return setTimeout(checkForMatch, 500)
}
}
return toggle === false ? (
<div onClick={flip}>
<div className='game-card-bg' >
<img src={bg} alt='card' style={{ width: '100%' }} />
</div>
</div>
):(
<div>
<div className='game-card' >
<img src={img} alt='card' />
<h4 className='card-name'>{name}</h4>
</div>
</div>
)
}
export default GameCard