import React from 'react'; import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, PieChart, Pie, Cell, BarChart, Bar, } from 'recharts'; // ========================= // 通用类型定义 // ========================= export interface SeriesConfig { key: string; name: string; color?: string; strokeWidth?: number; } export interface BaseChartProps { width?: number | string; height?: number; showGrid?: boolean; showLegend?: boolean; showTooltip?: boolean; backgroundColor?: string; className?: string; } // 默认颜色池 const DEFAULT_COLORS = [ '#1677ff', '#52c41a', '#fa8c16', '#eb2f96', '#722ed1', '#13c2c2', '#f5222d', '#2f54eb', ]; // ========================= // 折线图组件 // ========================= export interface UniversalLineChartProps extends BaseChartProps { data: Record[]; xKey: string; series: SeriesConfig[]; smooth?: boolean; dot?: boolean; xAxisLabel?: string; yAxisLabel?: string; } export const UniversalLineChart: React.FC = ({ data, xKey, series, width = '100%', height = 360, showGrid = true, showLegend = true, showTooltip = true, backgroundColor = '#ffffff', smooth = true, dot = false, className, }) => { return (
{showGrid && ( )} {showTooltip && } {showLegend && } {series.map((item, index) => ( ))}
); }; // ========================= // 柱状图组件 // ========================= export interface UniversalBarChartProps extends BaseChartProps { data: Record[]; xKey: string; series: SeriesConfig[]; barSize?: number; radius?: number | [number, number, number, number]; stack?: boolean; } export const UniversalBarChart: React.FC = ({ data, xKey, series, width = '100%', height = 360, showGrid = true, showLegend = true, showTooltip = true, backgroundColor = '#ffffff', barSize = 28, radius = 6, stack = false, className, }) => { return (
{showGrid && ( )} {showTooltip && } {showLegend && } {series.map((item, index) => ( ))}
); }; // ========================= // 饼图组件 // ========================= export interface PieDataItem { name: string; value: number; color?: string; } export interface UniversalPieChartProps extends BaseChartProps { data: PieDataItem[]; innerRadius?: number; outerRadius?: number; paddingAngle?: number; showLabel?: boolean; } export const UniversalPieChart: React.FC = ({ data, width = '100%', height = 360, showLegend = true, showTooltip = true, backgroundColor = '#ffffff', innerRadius = 60, outerRadius = 120, paddingAngle = 2, showLabel = true, className, }) => { return (
{showTooltip && } {showLegend && } {data.map((entry, index) => ( ))}
); }; // ========================= // 使用示例 // ========================= export const DemoCharts = () => { const lineData = [ { month: '1月', uv: 400, pv: 240, amt: 240 }, { month: '2月', uv: 300, pv: 456, amt: 300 }, { month: '3月', uv: 500, pv: 139, amt: 200 }, { month: '4月', uv: 278, pv: 390, amt: 278 }, { month: '5月', uv: 189, pv: 480, amt: 189 }, ]; const pieData = [ { name: 'Vue', value: 40 }, { name: 'React', value: 35 }, { name: 'Angular', value: 25 }, ]; return (
); };