我正在使用NextJS/Reaction开发一个简单的测试应用程序,最后我有一个问题.
代码如下:
Board.tsx文件内容:
'use client'
import './Board.css';
import {useState} from 'react';
export default function Board({count}:{count:number}) {
const [cellLights,setCellLights] = useState(Array.from({length:0},()=>
Array.from({length:0},()=>false)));
const refresh = () => {
let tempLights:boolean[][] = cellLights;
for (let idx=0; idx<tempLights.length; idx++) {
for (let idix=0; idix<tempLights[idx].length; idix++) {
tempLights[idx][idix] = false;
}
}
setCellLights(tempLights)
} /* End of refresh */
let rows:number[] = [];
while (rows.length<count) {rows.push(rows.length)}
let tempLights:boolean[][] = [];
rows.forEach(rowElt => {
let rowLights:boolean[] = [];
rows.forEach(colElt => {
rowLights.push(false)
});
tempLights.push(rowLights)
});
if (tempLights.length!=cellLights.length) setCellLights(tempLights)
return <div className="board">
{
rows.map(item => (
<div key={item}>
<Row count={count}
flags={cellLights[item]}
cleanFn={refresh}/>
</div>
))
}
</div>
} /* End of Board */
function Row({count,flags,cleanFn}:{count:number,flags:boolean[],cleanFn:()=>void}) {
let cells:number[] = [];
while (cells.length<count) {cells.push(cells.length)}
return <div className="row">
{
cells.map(item => (
<div key={item}>
<Cell flag={flags[item]}
cleanFn={cleanFn}/>
</div>
))
}
</div>
} /* End of Row */
function Cell({flag,cleanFn}:{flag:boolean,cleanFn:()=>void}) {
const [high, setHighFlag] = useState(flag);
function cellClick() {
cleanFn();
setHighFlag(!high)
}
return <>
{(!high) && <div className="cell" onClick={cellClick}/>}
{(high) && <div className="cell high" onClick={cellClick}/>}
</>
} /* End of Cell */
和Board.css文件内容:
.cell {
width: 3rem;
height: 3rem;
background-color: rgb(255, 255, 0);
border-width: 2px;
border-color: rgb(55, 55, 55);
margin:0.1rem;
}
.high {
background-color: rgb(255, 0, 0);
}
.row {
display: flex;
flex-direction: row;
}
.board {
display: flex;
flex-direction: column;
}
顶部是app/page.tsx文件:
import Image from 'next/image'
import Board from './components/Board'
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{/* // <main> */}
X4C APP
<Board count={3}/>
</main>
)
}
以下是运行该应用程序时,在单击两个正方形单元格后出现在网络浏览器中的内容:
现在我的问题来了.用户可以看到两个以红色突出显示的单元格.但这并不是我从我的代码中期望的.
由于当执行单击时,会调用cleanFn(),从而调用refresh(),因此我预计在最后单击的单元格变为红色之前,先前突出显示的单元格将恢复为其原始 colored颜色 (黄色).
看到截图,显然不是这样的.有人能看到代码中的缺陷在哪里吗?