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

React嵌套组件不渲染问题:50×50网格无法正常显示

解决React中Cell组件无法在Board组件内渲染的问题

你的问题核心是Board组件没有处理传入的子元素(children)。在Game组件中,你把Cell组件作为Board的子元素传递,但Board的JSX里没有渲染children这个props,所以这些Cell完全没有被挂载到DOM中,自然只能看到蓝色的背景容器。

修复步骤

1. 修改Board组件,渲染子元素

修改Board组件,接收children参数,并将其放在grid容器内部,同时把硬编码的尺寸值替换为传入的props,让组件更灵活:

import '../App.css'

export default function Board({ row, column, pix, children }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${column}, ${pix}px)`,
      gridTemplateRows: `repeat(${row}, ${pix}px)`,
    }}>
      {children} {/* 渲染传入的Cell子元素 */}
    </div>
  )
}

2. 修复Cell组件的clickAction警告

Cell组件声明了clickAction props,但Game中未传递该属性,会触发控制台警告。可以给Cell组件设置默认空函数:

export default function Cell({ value, colour, rowIndex, colIndex, clickAction = () => {} }) {
  return (
    <div
      onClick={(e) => clickAction(e, rowIndex, colIndex)}
      style={{
        border: '1px solid black',
        display: 'flex',
        placeContent: 'center center',
        alignItems: 'center',
        backgroundColor: colour,
      }}
    >{value}
    </div>
  )
}

3. 添加循环元素的key属性(必加)

React要求循环渲染的元素必须有唯一key,帮助React高效更新DOM,避免警告:

export default function Game() {
  const boardDimensions = {
    width: 50,
    height: 50
  }

  const array2D = Array(boardDimensions.height).fill().map((row) => Array(boardDimensions.width).fill(0))
  const [fiboCells, setFiboCells] = useState(array2D)

  return (
    <div className="center">
      <Board row={50} column={50} pix={25}>
        {
          fiboCells.map((row, i) => row.map((col, j) => (
            <Cell
              key={`${i}-${j}`} {/* 用行列索引组合作为唯一key */}
              value={col}
              rowIndex={i}
              colIndex={j}
              colour="red"
            />
          )))
        }
      </Board>
    </div>
  )
}

完成以上修改后,就能看到50×50的红色网格,每个单元格显示0。

内容的提问来源于stack exchange,提问作者Alex Vasconcelos de Almeida

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:22:24