import React, { useMemo } from 'react'; import { BaseChart, BaseChartProps } from './BaseChart'; import type { TouchEvent, ChartsConfig, LegendConfig } from '../lib/charts/index'; /** * 饼图类型 */ export type PieChartType = 'pie' | 'ring'; /** * 饼图组件的 Props 接口 */ export interface PieChartProps extends Omit { /** 饼图类型 */ pieType?: PieChartType; /** 是否显示图例 */ legend?: boolean; /** 字体大小 */ fontSize?: number; /** 背景颜色 */ background?: string; /** 是否开启动画 */ animation?: boolean; /** 是否显示数据标签 */ dataLabel?: boolean; /** 环形图内径比例 (0-1) */ ringWidth?: number; /** 额外饼图配置 */ extra?: ChartsConfig['extra']; /** tooltip 格式化函数 */ tooltipFormatter?: (item: any) => string; } /** * PieChart 饼图组件 * * 用于显示占比数据的饼图,支持普通饼图和环形图 */ export const PieChart: React.FC = (props) => { const { pieType = 'pie', legend = true, fontSize = 11, background = '#FFFFFF', animation = true, dataLabel = true, ringWidth = 0.6, extra = {}, tooltipFormatter, series = [], config = {}, ...baseProps } = props; const chartRef = React.useRef(null); /** * 默认配置 */ const defaultConfig = useMemo(() => { const legendConfig: LegendConfig = legend ? { show: true } : { show: false }; return { legend: legendConfig, fontSize, background, animation, dataLabel, extra: { pie: { activeOpacity: 0.5, activeRadius: 10, offsetAngle: 0, ringWidth: pieType === 'ring' ? ringWidth : 0, labelWidth: 15, ringWidthRatio: pieType === 'ring' ? ringWidth : 0 }, ...extra } }; }, [legend, fontSize, background, animation, dataLabel, pieType, ringWidth, extra]); /** * tooltip 事件处理 */ const handleTouchStart = (e: TouchEvent) => { if (chartRef.current) { if (tooltipFormatter) { chartRef.current.showToolTip(e, { formatter: tooltipFormatter }); } else { chartRef.current.showToolTip(e, { formatter: (item: any) => { return item.name + ':' + item.data; } }); } } baseProps.onTouchStart?.(e); }; return ( ); }; export default PieChart;