React ApexCharts Treemap的fontSize设置与多行文本失效问题
React ApexCharts Treemap 问题解决指南
问题1:dataLabels.style.fontSize 设置不生效
用户配置dataLabels时设置字体大小无效果:
dataLabels: { //enabled: true, style: { fontSize: "20px", }, }
解决方法:Treemap的dataLabels样式需配置在plotOptions.treemap下,而非全局dataLabels:
plotOptions: { treemap: { enableShades: false, dataLabels: { style: { fontSize: '20px' } } } },
问题2:多行字符串无法正常换行
用户尝试模板字符串换行无效:
return `${textList[0]} ${textList[1]} ${textList[2]}`
解决方法:开启HTML模式,用<br>标签实现换行:
dataLabels: { enabled: true, useHTML: true, formatter: function(text:string, o:datapointType){ let textList = text.split("\n"); return `${textList[0]}<br>${textList[1]}<br>${textList[2]}`; }, },
问题3:全局CSS设置字体导致文本溢出,overflow-wrap无效
用户添加全局样式后文本溢出:
.apexcharts-data-labels > text { font-size: 10px !important; overflow-wrap: break-word !important; }
解决方法:SVG文本元素不支持overflow-wrap,改用SVG兼容的white-space属性:
.apexcharts-data-labels text { font-size: 10px !important; white-space: pre-line !important; }
优先建议通过ApexCharts自身配置(如plotOptions.treemap.dataLabels.style)设置字体,避免全局样式冲突。
完整修正后的组件代码
import React from 'react'; import { ApexOptions } from "apexcharts"; import dynamic from 'next/dynamic'; import { getTenantDetails } from "utils/assetOverview"; const ReactApexChart = dynamic(() => import('react-apexcharts'), { ssr: false }); type datapointType = { value: number seriesIndex: number dataPointIndex: number } type tenantType = { x: string, y: number } const TreeMap: React.FC<{ areaChecked: boolean, assetCode: string }> = ({ areaChecked, assetCode }) => { let { tenantList } = getTenantDetails(assetCode); let tenants: tenantType[] = []; if (tenantList) { tenants = tenantList.map((tenant) => { if (areaChecked) { return { "x": `${tenant.name}\n${tenant.area}ft (${tenant.percentage}%)\n${tenant.years}`, "y": tenant.area } } else { return { "x": `${tenant.name}\n$${tenant.revenue} (${tenant.percentage}%)\n${tenant.years}`, "y": tenant.revenue } } }) } const series = [ { data: tenants } ] const options: ApexOptions = { legend: { show: false }, colors: ['#002776'], chart: { height: 260, toolbar: { show: false } }, plotOptions: { treemap: { enableShades: false, dataLabels: { style: { fontSize: '14px' // 可根据需求调整 } } } }, dataLabels: { enabled: true, useHTML: true, formatter: function (text: string, o: datapointType) { let textList = text.split("\n"); return `${textList[0]}<br>${textList[1]}<br>${textList[2]}`; } } } return ( <React.Fragment> <ReactApexChart options={options} series={series} type="treemap" height={260} /> </React.Fragment> ); } export default TreeMap;
内容的提问来源于stack exchange,提问作者Vandana
相关产品推荐
相关产品推荐

