我在这里遇到了一种情况,包括 React 使用加上 chart.js 库中的附加插件:chartjs-plugin-waterfall。
我必须为我的客户开发一个个性化的仪表板,直到现在我已经能够使用库 chartjs 及其 react 组件实现每种类型的 charts:react-chartjs-2。
但是我现在在最后一个必须实现的过程中挣扎了好几个小时——它不能作为“react-chart 组件”使用——:Waterfall chart。为此,我决定添加 chartjs-plugin-waterfall 并将其实现为新的 Chart (这里是代码示例):
const WaterFallType = () => {
let chart = false
useEffect(() => {
if(chart instanceof Chart) {
chart.destroy();
}
let ctx = document.getElementById("myChart").getContext('2d')
chart = new Chart(ctx, {
type: "bar",
plugins: [waterFallPlugin],
data :{
datasets: [
{
label: 'Closing Costs',
data: [50],
backgroundColor: '#e8cdd7',
stack: 'stack 1',
},
{
label: 'Purchase Price',
data: [700],
backgroundColor: '#d29baf',
stack: 'stack 1',
},
{
data: [200],
waterfall: {
dummyStack: true,
},
stack: 'stack 2',
},
{
label: 'Opening Loan Balance',
data: [550],
backgroundColor: '#bb6987',
stack: 'stack 2',
},
{
label: 'Initial Cash Investment',
data: [200],
backgroundColor: '#a53860',
stack: 'stack 3',
},
],
},
options: {
plugins: {
waterFallPlugin: {
stepLines: {
enabled: true,
startColorStop: 0,
endColorStop: 0.6,
startColor: 'rgba(0, 0, 0, 0.55)',
endColor: 'rgba(0, 0, 0, 0)',
diagonalStepLines: true,
},
},
},
}
})
}, [chart])
return <div>
<canvas id="myChart" width="400px" height="400px"></canvas>
</div>
}
export default WaterFallType
不幸的是,此代码不会呈现组件,而是会引发几个错误:
第一个:“未捕获的错误:画布已在使用中。在重新使用画布之前,必须销毁 ID 为“2”的 Chart。”
第二个:“未捕获的类型错误:无法设置未定义的属性(设置'过滤器')”
谁能帮我打这场仗?非常感谢您的帮助。
本杰明
回答1
终于找到了一个不需要任何插件的解决方案。 Chart.js 允许浮动条:https://www.chartjs.org/docs/3.2.1/samples/bar/floating.html
这使它更容易!
有一个美好的一天!