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

如何解决React中children传递对象数组的TypeScript类型错误

解决TypeScript期望ReactNode而非Array的语法错误

问题核心

你当前的写法存在两个关键问题:

  • React组件的children默认类型是ReactNode,不能直接把组件props的类型定义为Array<object>
  • 用children传递纯数据对象不符合React设计逻辑,容易和真正的React子元素混淆

正确实现方式

1. 定义菜单项的类型接口

先明确每个菜单数据的结构,同时把class改成className(JSX中不能使用class关键字):

interface MenuItem {
  text: string;
  href: string;
  className: string;
}

2. 修改TopBar组件的props定义

改用专门的menuItems属性接收菜单数据,避免滥用children:

// TopBar.tsx
import React from 'react';
import Link from 'next/link';
import ImgBlock from './ImgBlock'; // 假设你已定义该组件

interface MenuItem {
  text: string;
  href: string;
  className: string;
}

interface TopBarProps {
  menuItems: MenuItem[];
}

export default function TopBar({ menuItems }: TopBarProps) {
  return (
    <div className="pl-4 pr-16 flex items-center h-16 w-screen justify-between border-b-gray-200 border-2 fixed bg-white z-10">
      <ImgBlock src="/assets/svg/logo.png" width="7rem" height="4rem"/>
      <div className="flex gap-8 items-center">
        {menuItems.map((item, index) => (
          <Link key={index} className={item.className} href={item.href}>
            {item.text}
          </Link>
        ))}
      </div>
    </div>
  );
}

3. 修改page.tsx中的调用方式

把数组传给menuItems属性,不再作为children传递:

// page.tsx
...
<TopBar menuItems={[
    {text:"career",href:"",className:"p-0 m-0"},
    {text:"contact",href:"",className:"p-0 m-0"},
    {text:"patient registry",href:"/patient_registry",className:"custom-outline p-1 rounded-2xl px-4 hover:bg-black hover:text-white"}
]} />
...

若坚持使用children传递(不推荐)

如果一定要通过children传数组,需要手动断言类型,但这种写法不规范:

// TopBar.tsx
import React, { ReactNode } from 'react';

interface MenuItem {
  text: string;
  href: string;
  className: string;
}

export default function TopBar({ children }: { children: ReactNode }) {
  // 断言children为MenuItem数组,需确保传入数据类型匹配
  const menuItems = children as unknown as MenuItem[];
  
  return (
    <div className="pl-4 pr-16 flex items-center h-16 w-screen justify-between border-b-gray-200 border-2 fixed bg-white z-10">
      <ImgBlock src="/assets/svg/logo.png" width="7rem" height="4rem"/>
      <div className="flex gap-8 items-center">
        {menuItems.map((item, index) => (
          <Link key={index} className={item.className} href={item.href}>
            {item.text}
          </Link>
        ))}
      </div>
    </div>
  );
}

关键注意点

  • 避免使用object这种模糊类型,明确的接口能让TypeScript更好地检查错误
  • JSX中必须用className代替class,规避JavaScript关键字冲突
  • 优先用专门的props传递数据,children应留给真正的React元素

内容的提问来源于stack exchange,提问作者レノキ乇1ᑌᑭ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:42:41