因此,在ChartJS中使用自定义工具提示与React交互时会出现问题。
Example of current behaviour of custom tooltip
所以最初我用交互与相交:false对于我的图表,我希望在鼠标悬停在图表上时显示工具提示。但正如上面的视频所示,只有当我与数据集线及其下方的区域进行交互时,它才起作用,但即使我将鼠标悬停在这些线上,我也应该能够看到工具提示。
我的交互配置(这是最后一个,我已经尝试了很多组合,但真实的上它们对我来说并不像预期的那样工作):
interaction: {
intersect: false,
includeInvisible: true,
mode: 'nearest',
axis: 'x',
},
我还注意到,我的工具提示不透明度是0,当我把鼠标放在数据集线和它上面的区域时,我不知道为什么。用原来的工具提示它工作得很好。下面是我的自定义工具提示的代码:
tooltip: {
enabled: false,
external: ({ chart, tooltip }) => {
if (!chart) {
return;
}
if (tooltip.opacity === 0) {
setTooltipData(prevValue => ({ ...prevValue, visible: false }));
return;
}
// get coordinates of 2 points and get maximum of them to display tooltip according to it
const position = chart.canvas.getBoundingClientRect();
const maxX = Math.max(XusersPointPosition, XsubscribersPointPosition);
const maxY = Math.min(YusersPointPosition, YsubscribersPointPosition);
....................................................................................
setTooltipData({ top: maxY + offsetY, left: maxX + offsetX, label, data, visible: true });
}
这也是我的插件绘制虚线的X坐标的数据集点(我也认为这条线不工作,因为工具提示似乎是不透明度0,这就是为什么也不活跃,所以我们也看不到线)
export const plugins = [{
beforeDatasetsDraw: chart => {
// eslint-disable-next-line no-underscore-dangle
if (chart.tooltip._active && chart.tooltip._active.length) {
// find coordinates of tooltip
const [activePoint] = chart.tooltip._active;
const { ctx } = chart;
const { x, y } = activePoint.element;
const bottomY = chart.scales.y.bottom;
// draw vertical line
ctx.save();
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 1;
ctx.strokeStyle = '#718086';
ctx.setLineDash([4, 2]);
ctx.stroke();
ctx.restore();
}
},
}];
最后是工具提示本身的渲染
const NotificationStatisticsChart = ({ statistics }) => {
const [tooltipData, setTooltipData] = useState({
top: 0,
left: 0,
label: '',
data: null,
visible: false,
});
const data = useMemo(() => createDataObjectForChart(statistics), [statistics]);
const options = useMemo(() => createOptions(statistics, setTooltipData), [statistics]);
return (
<div className={styles.chart}>
<Line options={options} data={data} plugins={plugins} />
{visible ? (
<div className={styles.tooltip} style={{ top: top, left: left }}>
<div className={styles.date}>{tooltipLabel}</div>
{data.map(item => (
<div key={item.type} className={styles.amount}>
<span>{item.total}</span>
<span className={styles.count}>{item.delta}</span>
<span>{item.type}</span>
</div>
))}
</div>
) : null}
</div>
);
};
1条答案
按热度按时间lfapxunr1#
我终于解决了这个问题!所以问题是在悬停自定义工具提示本身,它导致了一些奇怪的行为。要解决这个问题,你只需要从你的工具提示中删除指针事件: