![](/img/trans.png)
[英]Integrate chartjs-chart-treemap with react-chartjs-2
[英]Integrate HTMLPlugin with react-chartjs-2 v4
我正在嘗試使用帶有 react-chartjs-2 的插件來使用定制的 Label。
這些是我正在使用的版本
"chart.js": "^3.9.1",
"react-chartjs-2": "^4.3.1",
"chartjs-plugin-datalabels": "^2.1.0",
重現代碼錯誤: https://codesandbox.io/s/hungry-feather-yj81gq
這就是我嘗試導入圖表和實例的方式
import {
ArcElement,
Chart as ChartJS,
Legend as ChartjsLegend,
Tooltip,
TooltipItem,
TooltipModel,
} from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { Doughnut } from 'react-chartjs-2';
我使用的示例已經在 Chartjs.org 的文檔中
https://www.chartjs.org/docs/3.9.1/samples/legend/html.html
這就是組件的樣子
const renderDoughnut = useCallback(() => {
const doughnutSize = 300;
return (
<Doughnut
data={{
labels,
datasets: [
{
hoverOffset: 6,
data,
backgroundColor: colors,
datalabels: {
anchor: 'center',
backgroundColor: null,
borderWidth: 0,
},
},
],
}}
width={doughnutSize}
height={doughnutSize}
options={{
responsive: false,
maintainAspectRatio: true,
plugins: {
htmlLegend: {
// ID of the container to put the legend in
containerID: 'legend-container',
},
datalabels: {
backgroundColor: null,
borderColor: 'white',
borderRadius: 25,
borderWidth: 2,
color: 'white',
display: () => true,
font: {
weight: 'bold',
},
padding: 3,
formatter: Math.round,
},
legend: {
display: false,
},
tooltip: tooltips,
},
}}
plugins={[htmlLegendPlugin]}
/>
);
}, [colors, data, labels, tooltips]);
/Users/reactnative/Sandbox/event-webapp/src/pages/home/Analytics/Components/Widgets/DoughnutChart/DoughnutChart.tsx 中的錯誤。/src/pages/home/Analytics/Components/Widgets/DoughnutChart/DoughnutChart.tsx 210 :12-213:13 [tsl] /Users/reactnative/Sandbox/event-webapp/src/pages/home/Analytics/Components/Widgets/DoughnutChart/DoughnutChart.tsx(210,13) TS2322 中的錯誤:類型 '{ htmlLegend :{容器ID:字符串; }; 數據標簽:{ 背景顏色:null; 邊框顏色:字符串; 邊界半徑:數字; 邊框寬度:數字; 顏色:字符串; 顯示:() => 真; 字體:{ 重量:“粗體”; }; 填充:數字; 格式化程序:(x:數字)=>數字; }; 傳奇: {...; }; 工具提示:{...; }; }' 不可分配給類型 '_DeepPartialObject<PluginOptionsByType<"doughnut">>'。 Object 文字可能只指定已知屬性,並且類型“_DeepPartialObject<PluginOptionsByType<"doughnut">>”中不存在“htmlLegend”。
有人可以展示將 htmlLegend 插件與 react-chartjs-2 一起使用嗎?
重現代碼錯誤: https://codesandbox.io/s/hungry-feather-yj81gq
謝謝
這里的問題是,您要告訴htmlLegendPlugin
查找 ID 為legend-container
,但該容器不存在。
htmlLegend: {
// ID of the container to put the legend in
containerID: "legend-container"
},
您可以解決向App.tsx
添加一個帶有 id legend-container
的簡單 div 的錯誤:
export function App() {
return (
<>
<div id="legend-container" />
<Doughnut
data={data}
options={{
responsive: false,
maintainAspectRatio: true,
plugins: {
htmlLegend: {
// ID of the container to put the legend in
containerID: "legend-container"
},
legend: {
display: false
}
}
}}
plugins={[htmlLegendPlugin]}
/>
</>
);
}
請參閱此處運行的示例: https://codesandbox.io/s/html-legend-plugin-chartjs-dn6eys
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.