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

使用map遍历数组渲染React子组件时出现对象无效错误求助

问题描述

我尝试使用React+Next.js+Tailwind开发计算器,但第一步就遇到问题。主页面代码如下:

import Screen from './component/Screen'
import Wrapper from './component/wrapper'
import ButtonBox from './component/buttonBox'
import Button from './component/button'
const btnValues=[
  ["C","+-","%","/"],
  [7,8,9,"*"],
  [4,5,6,"-"],
  [1,2,3,"+"],
  [0,".","="],
]
console.log(btnValues);
export default function Home() {

  return (
    <Wrapper>
     <Screen />
      <ButtonBox> 
        {btnValues.flat().map((btn,i)=>{ return (
          <Button value={btn} key={i}/>)}
        )}
      </ButtonBox>
    </Wrapper>
  )
}

遍历数组时触发错误:

"Internal error: Error: Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead."

ButtonBox组件代码:

const buttonBox = ({children}) => {
  return (
    <div className='mt-16'>
      {children}
    </div>
  )
}

export default buttonBox

Wrapper组件结构与ButtonBox一致,疑惑明明用了数组,为何还报错?


解决方案

错误根源不在Home组件的数组遍历,而是Button组件的实现问题——你没提供Button组件代码,但根据错误提示,它大概率直接渲染了整个props对象,而非传入的value属性值。

常见错误示例(Button组件):

// 错误写法:直接渲染props对象
const Button = (props) => {
  return <button>{props}</button>
}

这种写法会把包含value的props对象当成React子元素,触发"Objects are not valid as a React child"错误。

正确的Button组件写法:

提取value属性并渲染:

const Button = ({ value }) => {
  return <button className="your-tailwind-classes">{value}</button>
}

或者通过props对象访问:

const Button = (props) => {
  return <button className="your-tailwind-classes">{props.value}</button>
}

额外规范建议:

React组件名通常首字母大写,把ButtonBox组件的命名统一:

// 修改ButtonBox组件的定义与导出
const ButtonBox = ({children}) => {
  return (
    <div className='mt-16'>
      {children}
    </div>
  )
}

export default ButtonBox

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 18:33:25