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

如何将Rechart PieChart适配React TypeScript?正确声明Props方法

在React TypeScript中正确声明Rechart Pie组件activeShape的Props

Rechart官方已经为activeShape的回调函数提供了现成的TypeScript类型,直接使用即可,无需手动声明所有属性:

  • 首先从recharts包中导入对应的类型PieActiveShapeProps
  • 将renderActiveShape函数的props参数类型从any替换为PieActiveShapeProps
  • 如果你的数据有自定义结构,可以为payload指定更具体的类型,获得更精准的类型提示

修改后的完整代码示例

import { PieChart, Pie, PieActiveShapeProps } from 'recharts';

// 自定义你的数据类型(如果需要)
interface PieDataItem {
  name: string;
  value: number;
  // 其他你需要的字段
}

export const PieChartTab = () => {
    // 使用带泛型的PieActiveShapeProps指定payload类型
    const renderActiveShape = (props: PieActiveShapeProps<PieDataItem>) => {
        const { cx, cy, payload, fill } = props;

        return (
            <g>
                <text x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}>
                    {payload.name}
                </text>
            </g>
        );
    };

    return (
        <div>
            <PieChart width={230} height={230}>
                <Pie
                    activeShape={renderActiveShape}
                    data={dataAmHours as PieDataItem[]} // 这里也可以指定数据类型
                    cx={100}
                    cy={100}
                    blendStroke
                />
            </PieChart>
        </div>
    );
};

说明

  • PieActiveShapeProps包含了所有activeShape回调会收到的属性,比如cx、cy、payload、fill、innerRadius、outerRadius等,TypeScript会自动为你提供类型检查和补全。
  • 如果不需要自定义数据类型,直接使用PieActiveShapeProps不带泛型也可以,此时payload会被推断为Record<string, unknown>类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:54:22