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

TypeScript中如何为react-bootstrap的Card.Header的as属性定义prop类型

解决方案

你遇到的是React Bootstrap组件as属性的类型定义问题,不需要额外导入As类型,直接复用官方已导出的类型即可,有两种可行方案:

方案1:复用官方CardHeader内置类型(最推荐)

直接从react-bootstrap中取出CardHeaderProps的as属性类型,完全和官方定义对齐,类型安全度最高:

第一步:导入类型

import type { CardHeaderProps } from 'react-bootstrap/Card';

第二步:修改接口定义

export interface CollapseCardOptions {
  headerText: string;
  children: ReactElement;
  // 索引访问类型直接取CardHeader的as属性类型
  headerStyle?: CardHeaderProps['as'];
}

方案2:直接使用React内置元素类型

如果你不想额外导入react-bootstrap的类型,也可以直接用React内置的ElementType,覆盖绝大多数使用场景:

第一步:导入类型

import type { ElementType } from 'react';

第二步:修改接口定义

export interface CollapseCardOptions {
  headerText: string;
  children: ReactElement;
  headerStyle?: ElementType;
}

注:你当前的prop命名headerStyle存在歧义,该prop实际是用来指定Header渲染的元素类型(比如传'h1'就会渲染为h1标签),而非样式对象,建议重命名为headerAs提升代码可读性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:06:02