You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React实现4×4网格显示1-16数字及添加点击事件的方法

解决方案

一、显示1-16的数字

原代码里new Array(16).fill(1)会把数组所有元素都填充为1,所以map遍历的时候每个n都是1,自然无法显示1到16的连续数字。解决办法是利用map的第二个参数index(从0开始计数),通过index + 1就能得到1到16的对应数字。

二、添加点击事件并获取单元格数字

给每个div绑定onClick事件,在事件处理函数中直接传入当前单元格的数字,就能在函数里获取并使用这个值。

修改后的完整代码

function App() {
  // 单元格点击事件处理函数
  const handleCellClick = (number) => {
    console.log("点击的单元格数字:", number);
    // 这里可以添加你的业务逻辑,比如弹窗展示、状态更新等
  };

  return (
    <div style={{
      background: "#f0f0f0", // 加背景色方便查看边框
      height: "400px",
      width: "400px",
      display: "flex",
      flexWrap: "wrap"
    }}>
      {new Array(16).fill().map((_, index) => { 
        // 用_忽略第一个参数,我们只需要index来生成数字
        const cellNumber = index + 1;
        return (
          <div 
            key={index} // React列表渲染必须添加唯一key
            style={{
              height: "96px",
              width: "96px",
              backgroundColor: "transparent",
              border: "solid 2px white",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "24px",
              cursor: "pointer" // 鼠标移至单元格显示手型,提示可点击
            }}
            onClick={() => handleCellClick(cellNumber)} // 绑定点击事件并传递数字
          >
            {cellNumber}
          </div>
        );
      })}
    </div>
  );
}

export default App;

关键说明

  1. 数字生成:依赖map的index参数,index + 1直接生成1到16的连续数字,替代原代码中固定的n值。
  2. 点击事件:通过onClick={() => handleCellClick(cellNumber)}将当前单元格的数字传递给处理函数,在handleCellClick中可以直接获取并使用该数字。
  3. 列表key:React列表渲染要求每个子元素必须有唯一的key属性,这里用index作为key(也可以用唯一的cellNumber)。
  4. 样式优化:添加flex布局让数字居中,cursor: pointer提升交互提示性。

内容的提问来源于stack exchange,提问作者Tims

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:52:17