图像作为pointStyle与ChartJS在React中



我使用chartjs/react-chartjs-s在React/NextJS中绘制一些图。我想使用pointStyle的图像在一个特定的情节。在纯JavaScript中,可以使用const i = new Image()创建图像,并在ChartJS中用作pointStyle

在React我得到一个错误ReferenceError: Image is not defined。如果我尝试从next/image导入Image并使用它,那么图像不会出现在初始渲染(像这里有趣的可以使用new Image()),如果我点击图表上的数据,我会得到一个错误Error: Rendered more hooks than during the previous render.

TLDR:有没有人知道如何使用图像/图标作为pointStyle使用Next.js, ChartJS和react-chartjs-2?谢谢!

我用:

  1. reactv. 18.2.0
  2. react-domv. 18.2.0
  3. nextv 13.0.05
  4. chart.jsv. 4.1.1
  5. react-chartjs-2v. 5.1.0

解决方案:

new Image()引用DOM,但由于Next使用SSR,您必须利用useRefuseStateuseEffect钩子来规避尝试访问DOM的问题。

import React, { useEffect, useRef, useState } from "react";
import {
Chart as ChartJS,
RadialLinearScale,
PointElement,
LineElement,
Filler,
Tooltip,
Legend
} from "chart.js";
import { Radar } from "../node_modules/react-chartjs-2/dist";
ChartJS.register(
RadialLinearScale,
PointElement,
LineElement,
Filler,
Tooltip,
Legend
);
function App() {
// useRef lets you reference a DOM object, persistent between renders
const ref = useRef();
const [onClient, setOnClient] = useState();

// On first render, set onClient flag to true
useEffect(() => {
setOnClient(true);
}, []);
// On first render, set the current value of the ref to the image
useEffect(() => {
ref.current = new Image(25, 25);
ref.current.src = "https://i.stack.imgur.com/gXQrT.png";
}, []);
const data = {
labels: ["Business 1", "Business 2", "Business 3"],
datasets: [
{
label: "Number of Businesses",
data: [1300, 400, 160],
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgba(255, 99, 132, 1)",
borderWidth: 1,
// Set the value of pointStyle to the ref value
pointStyle: ref.current
}
]
};
return (
<div className="App">
// Return the graph if rendering is happening on the client
{onClient && <Radar data={data} />}
<form>
<input type="text" placeholder="Label" />
<input type="text" placeholder="Dataset" />
<button>Add Data</button>
</form>
</div>
);
}
export default App;

相关内容

  • 没有找到相关文章

最新更新