Skip to content

饼图

目的

此组件允许创建饼图和环形图。默认情况下,它已启用工具提示。源数据以数组形式存储在 data 字段中,而显示的分组则以对象形式存储在 series 字段中。扇形大小和颜色分别在 seriesfieldcolor 字段中定义。要创建环形图扇形,您需要指定 innerouter 字段,它们分别设置内半径和外半径。您可以在 TPieConfig 类型中找到所有可用设置。

用法

jsx
import { useState, useEffect } from 'react';
import { usePie } from 'effcharts/pie';

// 使用前定义自定义 Web 组件
// 注意,对于服务端渲染 (SSR),需要在浏览器解析文档主体之前调用它
// 因此,您可能需要在文档头部添加单独的定义脚本。
const { observe, getConfig } = usePie();

export const App = () => {
    const ref = useRef();
    const [config, setConfig] = useState(getConfig({
        data: [
            {
                name: 'Page A',
                uv: 4000,
                pv: 2400,
                color: 'green'
            },
            {
                name: 'Page B',
                uv: 3000,
                pv: 1398,
                color: 'red'
            },
            {
                name: 'Page C',
                uv: 2000,
                pv: 9800,
                color: 'blue'
            }
        ],
        series: {
            def: {
                field: 'uv',
                color: 'color',
                title: 'Default',
                inner: 0.55,
                outer: 1
            },
            sec: {
                field: 'pv',
                color: 'color',
                title: 'Secondary',
                outer: 0.5,
                angle: 180
            }
        }
    }));
    useEffect(() => {
        // 您可以观察 Web 组件事件
        const unobserve = observe((e) => {
            // 事件处理程序
        }, ref.current);
        // 你可以停止收听事件
        return () => unobserve();
    }, []);
    // 只需在 JSX 中使用 Web 组件即可
    return <div ref={ref}>
        <effcharts-pie config={config}>
        </effcharts-pie>
    </div>;
}

类型

您可以使用 IPieChartAttrs 接口声明 Web 组件。您还可以使用 TPieConfig 类型验证图表配置。

tsx
import { HTMLAttributes } from 'react';
import { IPieChartAttrs, TPieConfig } from 'effcharts/pie';

type CustomElement<T> = Partial<T & HTMLAttributes<T> & { children: any }>;

// 声明 effcharts 组件
declare module 'react' {
  namespace JSX {
    interface IntrinsicElements {
        'effcharts-pie': CustomElement<IPieChartAttrs>;
    }
  }
}

// 准备配置
const config = {
    data: [
        {
            name: 'Page A',
            uv: 4000,
            pv: 2400,
            color: 'green'
        },
        {
            name: 'Page B',
            uv: 3000,
            pv: 1398,
            color: 'red'
        },
        {
            name: 'Page C',
            uv: 2000,
            pv: 9800,
            color: 'blue'
        }
    ],
    series: {
        def: {
            field: 'uv',
            color: 'color',
            title: 'Default',
            inner: 0.55,
            outer: 1
        },
        sec: {
            field: 'pv',
            color: 'color',
            title: 'Secondary',
            outer: 0.5,
            angle: 180
        }
    }
} satisfies TPieConfig;

根据 Apache-2.0 许可证发布。