要创建一个可点击的方框网格,并且每个方框知道它们与哪些其他方框相邻,你可以使用React来构建这个组件。以下是一个基本的实现思路和示例代码:
以下是一个简单的React组件示例,展示了如何创建一个4x4的可点击方框网格,并且每个方框知道它们与哪些其他方框相邻。
import React, { useState } from 'react';
import './Grid.css';
const Grid = () => {
const [grid, setGrid] = useState(Array(4).fill().map(() => Array(4).fill(false)));
const handleClick = (row, col) => {
const newGrid = produce(grid, draft => {
draft[row][col] = !draft[row][col];
});
setGrid(newGrid);
};
const getNeighbors = (row, col) => {
const neighbors = [];
if (row > 0) neighbors.push([row - 1, col]);
if (row < 3) neighbors.push([row + 1, col]);
if (col > 0) neighbors.push([row, col - 1]);
if (col < 3) neighbors.push([row, col + 1]);
return neighbors;
};
return (
<div className="grid">
{grid.map((row, rowIndex) => (
<div key={rowIndex} className="row">
{row.map((cell, colIndex) => (
<div
key={colIndex}
className={`cell ${cell ? 'active' : ''}`}
onClick={() => handleClick(rowIndex, colIndex)}
>
{getNeighbors(rowIndex, colIndex).map(([nRow, nCol], index) => (
<span key={index}>[{nRow}, {nCol}]</span>
))}
</div>
))}
</div>
))}
</div>
);
};
export default Grid;
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
background-color: #ccc;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.cell.active {
background-color: #007bff;
}
useState
来管理网格的状态。handleClick
函数用于切换方框的状态。getNeighbors
函数用于获取当前方框的相邻方框。react-window
)来优化渲染。通过这种方式,你可以创建一个功能丰富的可点击方框网格,并且每个方框都能知道它们与哪些其他方框相邻。
领取专属 10元无门槛券
手把手带您无忧上云