我正在为一个项目使用 react-highchart。并显示两个图表:1) 带有 2 个系列数据的折线图,它将在同一图表上呈现两条线。2) 条形图或柱形图。
现在,当我将鼠标悬停在一个点上时,它应该在第一个图表和柱形图中的两条线上都启用工具提示。X 轴是日期时间。它应该像这样在两条线上活动点:
在 中react-highchart,我使用了shared: true属性,但它并没有使两行都处于活动状态。
tooltip: {
enabled: true,
useHTML: true,
shared: true,
backgroundColor: 'rgba(255,255,255,1)',
borderRadius: 3,
shape: 'rectangle'
}
有没有办法让另一个图表的工具提示也处于活动状态?
编辑
在提出建议后,我正在检查highcharts 中的同步图表,但代码示例是在 jQuery 中的,我需要它在react-highcharts. 我仍然尝试将代码转换为react并执行以下操作:
import ReactHighcharts from 'react-highcharts/ReactHighcharts';
/**
* Override the reset function, we don't need to hide the tooltips and
* crosshairs.
*/
ReactHighcharts.Highcharts.Pointer.prototype.reset = function reset() {
return undefined;
};
ReactHighcharts.Highcharts.Point.prototype.highlight = function highlight(event) {
event = this.series.chart.pointer.normalize(event);
this.onMouseOver(); // Show the hover marker
this.series.chart.tooltip.refresh(this); // Show the tooltip
this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the
crosshair
};
图表渲染回调后:
['mousemove', 'touchmove', 'touchstart'].forEach(eventType => {
const container = document.getElementById('tab__charts');
container.removeEventListener(eventType, this.handleMouseMove);
container.addEventListener(eventType, this.handleMouseMove);
});
处理鼠标移动和同步极端:
handleMouseMove(e) {
for (let i = 0; i < ReactHighcharts.Highcharts.charts.length; i += 1) {
const chart = ReactHighcharts.Highcharts.charts[i];
if (chart) {
// Find coordinates within the chart
const event = chart.pointer.normalize(e);
// Get the hovered point
const point = chart.series[0].searchPoint(event, true);
if (point) {
point.highlight(e);
}
}
}
}
syncExtremes(e) {
const thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
ReactHighcharts.Highcharts.each(ReactHighcharts.Highcharts.charts, (chart) => {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(
e.min,
e.max,
undefined,
false,
{ trigger: 'syncExtremes' },
);
}
}
});
}
}
现在,当我将鼠标悬停在该点上时,它会给出错误:
但不知何故它适用于第二个图表,如果我将鼠标悬停在第二个图表点上,它会在两个图表上显示工具提示。不适用于第一个图表。加上第一个图表有两个系列。我越来越接近解决方案了。
编辑 2:解决方案
我发现只有将鼠标悬停在第二个图表上时才会同步工具提示。这是由于那个控制台错误,它破坏了代码(里面的 For 循环handleMouseMove())。因此,在将该错误放入 后try catch,它解决了问题。
if (point) {
try {
point.highlight(e);
} catch (err) {
// pass;
}
}
不是最好的方法,但它有效。现在唯一的问题是,第一个图表有两条系列线(检查上图),只有第一个获得活动圆圈,而不是第二个。
编辑 3:突出显示多个系列的解决方案。
阅读代码后,我发现了这一行,它只导致第一个系列突出显示点:
point = chart.series[0].searchPoint(event, true)
这条线只采取第一个系列。糟糕的代码。它应该是:
chart.series.forEach(series => {
const point = series.searchPoint(event, true);
if (point) {
try {
point.highlight(e);
} catch (err) {
// pass;
}
}
});
现在唯一的问题是这个 try catch,没有得到Can not read property category of undefined.

