首页 > 解决方案 > 你如何映射一个数组并将每个数字分配给一个 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

标签: reactjs

解决方案


尝试这个:

grid.map((currentGrid)=>(
    console.log(currentGrid);
));

注意:在我的箭头函数之后,我没有使用花括号,而是使用了括号。


推荐阅读