| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import React, { useMemo } from 'react';
- import { BaseChart, BaseChartProps } from './BaseChart';
- import type { TouchEvent, LegendConfig, XAxisConfig, YAxisConfig } from '../lib/charts/index';
- /**
- * 柱状图类型
- */
- export type ColumnType = 'group' | 'stack';
- /**
- * 柱状图组件的 Props 接口
- */
- export interface ColumnChartProps extends Omit<BaseChartProps, 'type'> {
- /** 是否显示数据标签 */
- dataLabel?: boolean;
- /** 柱状图类型 */
- columnType?: ColumnType;
- /** X 轴配置 */
- xAxis?: XAxisConfig;
- /** Y 轴配置 */
- yAxis?: YAxisConfig;
- /** 图例是否显示 */
- legend?: boolean;
- /** 字体大小 */
- fontSize?: number;
- /** 背景颜色 */
- background?: string;
- /** 是否开启动画 */
- animation?: boolean;
- /** tooltip 格式化函数 */
- tooltipFormatter?: (item: any, category: string) => string;
- }
- /**
- * ColumnChart 柱状图组件
- *
- * 用于显示分类数据的柱状图,支持分组和堆叠模式
- */
- export const ColumnChart: React.FC<ColumnChartProps> = (props) => {
- const {
- dataLabel = true,
- columnType = 'group',
- xAxis,
- yAxis,
- legend = true,
- fontSize = 11,
- background = '#FFFFFF',
- animation = true,
- tooltipFormatter,
- categories = [],
- series = [],
- config = {},
- ...baseProps
- } = props;
- const chartRef = React.useRef<any>(null);
- /**
- * 默认配置
- */
- const defaultConfig = useMemo(() => {
- const legendConfig: LegendConfig = legend ? { show: true } : { show: false };
- const result = {
- legend: legendConfig,
- fontSize,
- background,
- animation,
- dataLabel,
- xAxis: xAxis ?? { disableGrid: true },
- yAxis: yAxis ?? {},
- extra: {
- column: {
- type: columnType,
- width: columnType === 'group'
- ? (baseProps.width ? baseProps.width * 0.45 / (categories.length || 1) : 20)
- : undefined
- }
- }
- };
- return result
- }, [legend, fontSize, background, animation, dataLabel, xAxis, yAxis, columnType, categories.length, baseProps.width]);
- /**
- * tooltip 事件处理
- */
- const handleTouchStart = (e: TouchEvent) => {
- if (chartRef.current && tooltipFormatter) {
- chartRef.current.showToolTip(e, {
- formatter: tooltipFormatter
- });
- } else if (chartRef.current) {
- chartRef.current.showToolTip(e, {
- formatter: (item: any, category: string) => {
- return category + ' ' + item.name + ':' + item.data;
- }
- });
- }
- baseProps.onTouchStart?.(e);
- };
- const finalConfig = { ...defaultConfig, ...config }
- return (
- <BaseChart
- {...baseProps}
- categories={categories}
- series={series}
- type="column"
- config={finalConfig}
- onTouchStart={handleTouchStart}
- />
- );
- };
- export default ColumnChart;
|