[英]Custom tooltip React ChartJs
I'm having an issue while creating a custom tooltip using react-chartjs-2 library where my chart rerenders whenever I hover the chart and change the state of the tooltip's future data.我在使用 react-chartjs-2 库创建自定义工具提示时遇到问题,每当我 hover 图表并更改工具提示的未来数据的 state 时,我的图表都会重新呈现。 (currently tooltip doesn't exist I'm simply logging some data which Ill use later) (目前工具提示不存在我只是记录一些我稍后会用到的数据)
I referenced this question while trying to create a tooltip however they are using a class component and I use functional component but it shouldn't really change anything but anyway.我在尝试创建工具提示时引用了这个问题,但是他们使用的是 class 组件,而我使用的是功能组件,但无论如何它都不应该真正改变任何东西。 I'd be really grateful of someone could provide a working example of a custom tooltip with react-chartjs-2 because I'm still not sure whether tooltip should be a separate jsx component or what is the proper way to create a custom tooltip in React.我真的很感激有人可以使用 react-chartjs-2 提供自定义工具提示的工作示例,因为我仍然不确定工具提示是否应该是一个单独的 jsx 组件,或者在中创建自定义工具提示的正确方法是什么反应。 Thanks in advance提前致谢
My code我的代码
const GraphTooltip = ({ data }) => {
return (
<div
style={{
padding: 20,
position: 'absolute',
border: '1px solid',
borderColor: '#fff8f9',
backgroundColor: 'rgba(53,53,53,0.81)',
borderRadius: 4,
top: data.top,
left: data.left,
}}
></div>
);
};
const LineChart = ({ values, labels }) => {
const isSSR = useIsSSR();
const [tooltipData, setTooltipData] = useState(null);
console.log(tooltipData);
const chartRef = useRef(null);
const customTooltip = useCallback(tooltipModel => {
if (tooltipModel.tooltip.opacity == 0) {
setTooltipData(null);
console.log('Hide tooltip');
return;
}
console.log(tooltipModel);
const chart = chartRef.current;
const canvas = chart.canvas;
console.log(canvas);
if (canvas) {
const position = canvas.getBoundingClientRect();
// set position of tooltip
const left = tooltipModel.tooltip.x;
console.log(position.left);
console.log(tooltipModel.tooltip);
const top = tooltipModel.tooltip.y;
tooltipData?.top != top && setTooltipData({ top: top, left: left });
}
});
const options = useMemo(() => ({
scales: {
x: {
ticks: {
beginAtZero: true,
},
grid: {
color: '#EEF5FF',
},
},
y: {
grid: {
color: '#EEF5FF',
},
},
},
plugins: {
legend: {
display: false,
position: 'right',
},
tooltip: {
enabled: false,
external: customTooltip,
},
},
}));
const data = {
labels: labels,
datasets: [
{
data: values,
fill: false,
backgroundColor: '#88B1DD',
borderColor: '#88B1DD',
pointRadius: 6,
tension: 0.5,
},
],
};
if (isSSR) return null;
return (
<>
<div className="header"></div>
<div className="relative">
<Line data={data} options={options} ref={chartRef} />
{tooltipData ? <GraphTooltip data={tooltipData} /> : <div />}
</div>
</>
);
};
Using https://www.npmjs.com/package/test-react-chartjs-2 actually fixed this.使用https://www.npmjs.com/package/test-react-chartjs-2实际上解决了这个问题。 Some problems in the package itself. package本身的一些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.