【问题标题】:How to show tooltip on legend hover?如何在图例悬停时显示工具提示?
【发布时间】:2021-10-02 16:53:32
【问题描述】:

我在 React 中使用 chart.js。

我已阅读并实施: Chart.js - show tooltip when hovering on legend

很遗憾,这并没有提供预期的结果。我相信这是因为这是在 javascript 中实现的,并且我正在实现 react。不确定这是否会影响任何事情。

const data = {
    labels: ['One', 'Two', 'Three'],
    datasets: [{
      data: [4, 5, 3],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
      hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
      borderWidth: 1,
      hoverBorderWidth: 3
    }]
  };
  const options = {
    plugins: {
      legend: {
        onHover: (evt: any, legendItem: any, legend: any) => {
          const index = legend.chart.data.labels.indexOf(legendItem.text);
          const activeSegment = legend.chart.getDatasetMeta(0).data[index];
          // console.log(activeSegment);
          // activeSegment.options.backgroundColor = activeSegment._options.hoverBackgroundColor;
          // activeSegment.options.borderWidth = activeSegment._options.hoverBorderWidth;
          legend.chart.tooltip._active = [activeSegment];
          legend.chart.update();
          legend.chart.draw();
        },
        onLeave: (evt: any, legendItem: any, legend: any) => {
          const index = legend.chart.data.labels.indexOf(legendItem.text);
          // const activeSegment = legend.chart.getDatasetMeta(0).data[index];
          // activeSegment.options.backgroundColor = activeSegment._options.backgroundColor;
          // activeSegment.options.borderWidth = activeSegment._options.borderWidth;
          legend.chart.tooltip._active = [];
          legend.chart.update();
          legend.chart.draw();
        }
      },
    },

  }

该组件的末尾返回以下内容:

return <Doughnut data={data} options={options} />;

这会生成我链接的 stackoverflow 帖子中显示的图表。

【问题讨论】:

  • 你用什么库/包来渲染图表 react-chartjs-2 或 chart.js ?
  • react-chart-js-2 @monesul haque

标签: reactjs chart.js tooltip legend onhover


【解决方案1】:

对于 v3,您可以使用一种方法以编程方式设置工具提示

 onHover: (evt, item, legend) => {
          const chart = legend.chart;
          const tooltip = chart.tooltip;

          const chartArea = chart.chartArea;
          tooltip.setActiveElements([{
            datasetIndex: 0,
            index: item.index,
          }], {
            x: (chartArea.left + chartArea.right) / 2,
            y: (chartArea.top + chartArea.bottom) / 2,
          });


          chart.update();
        },

【讨论】:

  • 这解决了当我将鼠标悬停在图例标签上时显示工具提示的问题,但是我无法快速将鼠标悬停在标签之间。你知道一个可能的解决方案吗?例如,将鼠标悬停在图例中的“一”上并快速切换到“二”将导致“二”工具提示不出现。
猜你喜欢
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
相关资源
最近更新 更多