reactjs - 你如何映射一个数组并将每个数字分配给一个 div?
问题描述
使用此代码,我正在创建一个 10x10 的数组,其中一些字段的数字为 1,而其他字段的数字为零。我希望在每次<div>
单击时分配一个可以是 1 或 0 的数组值。因为为了创建<div>
网格,我们还需要获取网格的长度并创建一个 10x10 的网格。我尝试过映射数组,但每次单击后,整个数组都会记录在控制台中,而不仅仅是分配给它的一个值。
import React, {useEffect ,useState} from 'react'
import Ship from '../components/ShipGenerate.js'
import '../style/style.css'
function Grid(props) {
const emptyGrid = new Array(10);
for (let i = 0; i < emptyGrid.length; i += 1) {
emptyGrid[i] = new Array(10).fill(0);
}
const rnd = r => Math.trunc(Math.random() * r);
// Here I've tried mapping over the array but it returns the whole array
function detectArray() {
grid.map((currentGrid) => {
console.log(currentGrid)
})
}
for (let l=0; l<40;l +=1) {
emptyGrid[rnd(10)][rnd(10)] = 1;
}
console.log(emptyGrid)
const [grid, setGrid] = useState(emptyGrid);
function togglePieceStatus(e) {
document.getElementById("piece").addEventListener("click", (e) => {
e.target.className = "boom"
})
}
const box = [];
console.log(box)
for (let x = 0; x < grid.length; x++) {
for (let y = 0; y < grid.length; y++) {
box.push(
<div>
// here is where I want to assign it a number of the array
<div
onClick = {() => detectArray()}
className="piece"
></div>
</div>
)
}
}
return (
<div>
<div id="piece" onClick={togglePieceStatus} className="box">{box}</div>
</div>
);
}
export default Grid
解决方案
尝试这个:
grid.map((currentGrid)=>(
console.log(currentGrid);
));
注意:在我的箭头函数之后,我没有使用花括号,而是使用了括号。
推荐阅读
- string - 多次拆分列中的字符串
- ios - Firebase 参考以 NSException 类型的未捕获异常引发终止
- node.js - 集合名称在reactjs和mogoDB中自动转换为复数?
- angular - 依赖项的 Angular Material 抛出错误
- xcode - 需要帮助从选取器视图数据中进行选择来执行计算
- javascript - 通过循环的承诺服务器调用的不一致行为
- swift - 节点位置卡在原点
- html - 如何在左上角制作内部div位置
- python - 如何使用变量生成带有 python-barcode 的条形码
- java - 将适配器设置为微调器会将回收器视图滚动到顶部