You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在antv/g6的g6-react-node <Text>中实现类似CSS word-wrap的换行

解决G6 React自定义节点中文本自动换行的问题

G6的<Text>组件基于SVG实现,不支持CSS的flex-wrap这类HTML布局属性,所以你原来的配置不会生效。可以通过以下两种方式实现文本自动换行:

方法一:使用G6内置的文本换行属性

直接给<Text>组件添加textWrap配置,指定换行宽度和换行规则:

<Group>
  <Rect
    style={{
      width: 100,
      height: 70, 
      fill: 'l(0) 0:#D67200 1:#FABD55',
      radius: 6,
    }}
  />
  <Text 
    style={{
      fill: "#FFF", 
    }}
    textWrap={{
      width: 90, // 比节点宽度小一点,留出内边距
      overflow: 'break', // 超出宽度自动换行
      ellipsis: false // 不需要省略号则设为false
    }}
  >
    {label}
  </Text>
</Group>

说明:

  • textWrap.width设置触发换行的最大宽度,建议比节点Rect的width小一些,避免文本贴边
  • overflow: 'break'会自动在字符/单词边界换行(中文自动按字符拆分)
  • 若需要超出部分显示省略号,可将ellipsis设为true

方法二:手动拆分文本为多行

如果需要更精细的控制,可以提前将文本按指定宽度拆分成多行,用<Tspan>组件实现:

import { Group, Rect, Text, Tspan } from '@antv/g6-react-node';

// 工具函数:按宽度拆分文本为多行
const splitText = (text, maxWidth, ctx) => {
  const words = text.split('');
  const lines = [];
  let currentLine = '';
  for (const word of words) {
    const testLine = currentLine + word;
    const metrics = ctx.measureText(testLine);
    if (metrics.width > maxWidth && currentLine) {
      lines.push(currentLine);
      currentLine = word;
    } else {
      currentLine = testLine;
    }
  }
  lines.push(currentLine);
  return lines;
};

// 自定义节点组件
const CustomNode = ({ label }) => {
  const maxWidth = 90;
  // 创建canvas上下文用于计算文本宽度,需与Text组件字体样式一致
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.font = '14px sans-serif';
  const lines = splitText(label, maxWidth, ctx);

  return (
    <Group>
      <Rect
        style={{
          width: 100,
          height: 70, 
          fill: 'l(0) 0:#D67200 1:#FABD55',
          radius: 6,
        }}
      />
      <Text style={{ fill: "#FFF" }}>
        {lines.map((line, index) => (
          <Tspan key={index} dy={index === 0 ? 0 : 20} x={5}>
            {line}
          </Tspan>
        ))}
      </Text>
    </Group>
  );
};

说明:

  • dy控制每行的垂直间距,需根据字体大小调整
  • x设置文本水平偏移,实现内边距效果
  • 测量文本时的字体样式必须与<Text>组件一致,否则宽度计算会出现偏差

额外提示

如果需要节点高度随文本行数自适应,可以在计算出多行文本后,动态设置Rect的height属性,例如height: 40 + lines.length * 20(基础高度+每行高度)。

内容的提问来源于stack exchange,提问作者TBuddhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:55:01