React highchart:相同和不同图表中的共享工具提示

时间:2018-11-08 09:52:26

标签: javascript reactjs charts highcharts react-highcharts

我正在为项目使用react-highchart。并显示两个图表: 1)带有2个系列数据的折线图,它将在同一张图表上绘制两条线。 2)条形图或柱形图。

现在,当我将鼠标悬停在一个点上时,它应该在第一张图表和柱状图中的两条线上都启用工具提示。 X轴是日期时间。 应该在两行上都这样激活点:

enter image description here

react-highchart中,我使用了shared: true属性,但没有使两条线都处于活动状态。

tooltip: {
  enabled: true,
  useHTML: true,
  shared: true,
  backgroundColor: 'rgba(255,255,255,1)',
  borderRadius: 3,
  shape: 'rectangle'
}

有没有办法使另一个图表的工具提示也处于活动状态?

编辑

在提出建议之后,我正在检查图表中的synchronized-charts,但是代码示例在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);
});

处理鼠标移动并同步极端:

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' },
          );
        }
      }
    });
  }
}

现在,当我将鼠标悬停在该点上时,它将给出错误:

enter image description here

但是不知何故,它适用于第二张图表,如果我将鼠标悬停在第二张图表上,它将在两个图表上显示工具提示。不适用于第一个图表。再加上第一个图表有两个系列。我正在接近解决方案。

编辑2:解决方案 我发现,仅当将鼠标悬停在第二张图表上时,才导致工具提示同步的原因。这是由于该控制台错误导致代码中断(handleMouseMove()中的For循环)。因此,将错误放入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;
        }
    }
});

现在唯一的问题是尝试捕获,而没有得到Can not read property category of undefined

1 个答案:

答案 0 :(得分:1)

我建议您使用highcharts-react-official包装器。您可以在下面找到同步图表的示例:

import React from "react";
import { render } from "react-dom";
// Import Highcharts
import Highcharts from "highcharts/highstock";
//import HighchartsReact from "./HighchartsReact.min.js";
import HighchartsReact from "highcharts-react-official";

(function(H) {
  H.Pointer.prototype.reset = function() {
    return undefined;
  };

  /**
   * Highlight a point by showing tooltip, setting hover state and draw crosshair
   */
  H.Point.prototype.highlight = function(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
  };

  H.syncExtremes = function(e) {
    var thisChart = this.chart;

    if (e.trigger !== "syncExtremes") {
      // Prevent feedback loop
      Highcharts.each(Highcharts.charts, function(chart) {
        if (chart && chart !== thisChart) {
          if (chart.xAxis[0].setExtremes) {
            // It is null while updating
            chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, {
              trigger: "syncExtremes"
            });
          }
        }
      });
    }
  };
})(Highcharts);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: {
        chart: {
          type: "line",
          zoomType: "x",
          panning: true,
          panKey: "shift"
        },
        xAxis: {
          events: {
            setExtremes: function(e) {
              Highcharts.syncExtremes(e);
            }
          }
        },
        series: [
          {
            data: [
              29.9,
              71.5,
              106.4,
              129.2,
              144.0,
              176.0,
              135.6,
              148.5,
              216.4,
              194.1,
              95.6,
              54.4
            ]
          }
        ]
      },
      options2: {
        chart: {
          zoomType: "x"
        },
        series: [
          {
            data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
          }
        ],
        xAxis: {
          events: {
            setExtremes: function(e) {
              Highcharts.syncExtremes(e);
            }
          }
        }
      }
    };
  }

  componentDidMount() {
    ["mousemove", "touchmove", "touchstart"].forEach(function(eventType) {
      document
        .getElementById("container")
        .addEventListener(eventType, function(e) {
          var chart, point, i, event;

          for (i = 0; i < Highcharts.charts.length; i = i + 1) {
            chart = Highcharts.charts[i];
            if (chart) {
              // Find coordinates within the chart
              event = chart.pointer.normalize(e);
              // Get the hovered point
              point = chart.series[0].searchPoint(event, true);

              if (point) {
                point.highlight(e);
              }
            }
          }
        });
    });
  }

  inputChange(e) {
    this.setState({
      options: {
        series: [{ data: [1, 1, 1] }, { data: [2, 2, 2] }]
      }
    });
  }

  render() {
    return (
      <div id="container">
        <HighchartsReact
          constructorType={"chart"}
          highcharts={Highcharts}
          options={this.state.options}
        />
        <HighchartsReact
          constructorType={"chart"}
          highcharts={Highcharts}
          options={this.state.options2}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

实时演示:https://codesandbox.io/s/jl8mrq2m53