我使用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?谢谢!
我用:
react
v. 18.2.0react-dom
v. 18.2.0next
v 13.0.05chart.js
v. 4.1.1
react-chartjs-2
v. 5.1.0解决方案:
new Image()
引用DOM,但由于Next使用SSR,您必须利用useRef
、useState
和useEffect
钩子来规避尝试访问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;