【发布时间】:2022-10-01 01:39:17
【问题描述】:
所以我正在尝试将宾果游戏实现为一个小型入门反应项目。如果用户得到一个词,那么我希望他们能够单击该框并且样式会更改,以便该框以绿色突出显示,例如。
我目前对这种工作的实现,它改变了框的颜色,但是当我尝试重置并按下“新游戏”时,一些框仍然突出显示并且没有被重置。
我尝试将一个重置道具传递给组件以重置状态,但这并没有奏效,所以我很困惑......
关于我可以做什么的任何想法?
这是我的 app.js
import { useState, useEffect } from \'react\'
import \'./App.css\';
import Cell from \'./components/Cell\';
function App() {
const [words, setWords] = useState([])
const [reset, setReset] = useState(false)
const groupOfWords = [
{ \"word\": \"hello\", id: 1},
{ \"word\": \"react\", id: 2},
{ \"word\": \"gaming\", id: 3},
{ \"word\": \"university\", id: 4},
{ \"word\": \"yoooo\", id: 5},
{ \"word\": \"hockey\", id: 6},
{ \"word\": \"programming\", id: 7},
{ \"word\": \"xbox\", id: 8},
{ \"word\": \"digging\", id: 9},
{ \"word\": \"car\", id: 10}
]
const pickRandomWords = () => {
setReset(true)
// Shuffle array
const shuffled = groupOfWords.sort(() => 0.5 - Math.random())
// Get sub-array of first n elements after shuffled
setWords(shuffled.slice(0, 8))
}
return (
<div className=\"App\">
<h1>Bingo</h1>
<button onClick={pickRandomWords}>New Game</button>
<div className=\'grid\'>
{words.map(w => (
<Cell
key={w.id}
word={w.word}
reset={reset}/>
))}
</div>
</div>
);
}
export default App;
这是我的细胞组件
import \'./Cell.css\'
import { useState } from \'react\'
export default function Cell({ word, reset }) {
const [matched, setMatched] = useState(reset)
const highlightCell = () => {
setMatched(true)
}
return (
<div className={matched ? \'cell\' : \'cellMatched\'} onClick={highlightCell}>
<p>{word}</p>
</div>
)
}
-
当你可以使用
setWords([])来重置游戏时,为什么你甚至需要这个reset状态。你的setWords(shuffled.slice(0, 8))也应该足够了 -
所以我之前也有过这样的想法,但是当我开始一个新游戏时 - 网格的单元格会记住它们的状态并保持突出显示
-
您应该将这个
matched状态向上移动。或者运行useEffect,它将在每次word更改时清除matched -
是的,有趣的是,我想到了第二个选项并尝试了它,但它并没有让我惊讶,但我尝试了与 app.js 匹配的移动
标签: javascript reactjs react-hooks