我正在为一个项目使用 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
. 我仍然尝试将代码转换为做出反应并这样做:
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);
});
处理鼠标移动和同步Extreme:
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 loop inside 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
.