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

React-ChartJS-2环形图修改图例位置报错的解决方案咨询

问题解决:React-ChartJS-2环形图切换图例位置至左右时报错

问题原因

报错的核心原因是你在图例配置中使用了boxHeight属性,但Chart.js的图例规则明确:仅当图例位置为top或bottom时,boxHeight才是合法配置项;当位置切换为left或right时,该属性不存在,直接设置会触发属性未定义的错误。折线图、柱状图未出现此问题,是因为它们的图例渲染逻辑对无效配置有兼容处理,而环形图没有。

修复方案

移除图例labels中的boxHeight配置即可解决问题。如果需要在上下位置时保留该样式,可以通过条件判断动态设置配置。

修复后的代码

import React from 'react'
import { Doughnut } from 'react-chartjs-2'
import { CategoryScale } from 'chart.js'; 
import Chart from 'chart.js/auto'
Chart.register(CategoryScale);

export default function DoughnutChart() {
    const data = [
        { year: 2010, count: 10 },
        { year: 2011, count: 20 },
        { year: 2012, count: 15 },
        { year: 2013, count: 25 },
    ];

    // 可切换为top/right/bottom
    const legendPosition = 'left';

    return (
        <Doughnut
            data={{
                labels: data.map(row => row.year),
                datasets: [
                    {
                        data: data.map(row => row.count)
                    }
                ],
            }}
            options={{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: legendPosition,
                        align: 'center',
                        labels: {
                            font: { size: 14 },
                            color: '#000',
                            usePointStyle: true,
                            boxWidth: 20,
                            // 仅在上下位置时设置boxHeight
                            ...(legendPosition === 'top' || legendPosition === 'bottom' ? { boxHeight: 7 } : {})
                        }
                    }
                }
            }}
        />
    )
}

注:原代码中color: '#000;'多了一个冗余分号,建议修正为color: '#000'以保持格式正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:30:13