logo

F2

  • 教程
  • 组件API
  • 图表示例
  • 所有产品antv logo arrow
  • 5.10.0
  • 快速上手
  • 核心概念
  • 图形语法
  • 数据处理
  • 度量
  • 坐标系
  • 图形标签 - Shape
  • 绘图属性 - Style
  • 动画属性 - Animation
  • 事件属性 - Event
  • 图形使用 - JSX
  • 自定义组件
  • 多端/框架 - Framework
    • 多端适配
    • 如何在 React 中使用
    • 如何在 Vue 中使用
    • 如何在小程序中使用
    • 如何在 Node.js 中使用
    • 配置 JSX Transform
    • 使用 SVG 渲染
  • 进阶 - Advanced
    • 自定义 View
  • 常见问题 - Question
    • 和 React 同时使用时,TS 类型报错

自定义 View

上一篇
使用 SVG 渲染
下一篇
和 React 同时使用时,TS 类型报错

资源

Ant Design
Galacea Effects
Umi-React 应用开发框架
Dumi-组件/文档研发工具
ahooks-React Hooks 库
WeaveFox-前端智能研发

社区

体验科技专栏
seeconfSEE Conf-蚂蚁体验科技大会
weavefoxWeaveFox-智能研发技术社区

帮助

GitHub
StackOverflow

more products更多产品

Ant DesignAnt Design-企业级 UI 设计语言
yuque语雀-知识创作与分享工具
EggEgg-企业级 Node 开发框架
kitchenKitchen-Sketch 工具集
GalaceanGalacean-互动图形解决方案
weavefoxWeaveFox-前端智能研发
© Copyright 2026 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

在 F2 中,为了让显示更加灵活和自定义,我们把所有的组件都进行了高阶组件(HOC)的封装,形成了 withXXX 的逻辑封装。下面以 Legend 为例,来演示如何实现自定义 View。

Legend 的使用

import { Canvas, Chart, Legend } from '@antv/f2';
<Canvas context={context}>
<Chart data={data}>
<Legend position="top" />
</Chart>
</Canvas>

除了 Legend 之外,还有 withLegend 和 LegendView 这两个对象,而 Legend = withLegend(LegendView)。所以我们只要定义自己的 LegendView 就能达到自定义 View 的效果。

定义自定义 View

const CustomLegendView = (props) => {
const { items } = props;
return (
<group
style={{
flexDirection: 'row',
}}
>
{items.map((item) => {
const { name, color } = item;
return (
<text
style={{
text: name,
fill: color,
}}
/>
);
})}
</group>
);
}

使用自定义 View

import { Canvas, Chart, withLegend } from '@antv/f2';
// 自定义 View
const CustomLegendView = (props) => {
const { items } = props;
return (
<group
style={{
flexDirection: 'row',
}}
>
{items.map((item) => {
const { name, color } = item;
return (
<text
style={{
text: name,
fill: color,
}}
/>
);
})}
</group>
);
}
// 使用自定义 view 的组件
const Legend = withLegend(CustomLegendView);
<Canvas context={context}>
<Chart data={data}>
<Legend position="top" />
</Chart>
</Canvas>

在 CustomLegendView 中,用户可以拿到计算逻辑后的结果 props,也可以使用 Legend 组件的 public function。

完整示例

  • 自定义 Legend