| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- 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<BaseChartProps, 'type' | 'categories'> {
- /** 饼图类型 */
- 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<PieChartProps> = (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<any>(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 (
- <BaseChart
- {...baseProps}
- series={series}
- type={pieType}
- config={{ ...defaultConfig, ...config }}
- onTouchStart={handleTouchStart}
- />
- );
- };
- export default PieChart;
|