如何在图例悬停时显示工具提示? [英] How to show tooltip on legend hover?

查看:45
本文介绍了如何在图例悬停时显示工具提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 中使用 chart.js.

I am using chart.js in React.

我已阅读并实施:Chart.js - 悬停时显示工具提示传说中的

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

Unfortunately, this is not providing the desired results. I believe this is because this is being implemented in javascript, and I am implementing react. Not sure if that is impacting anything.

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

  }

此组件的结尾返回以下内容:

with the end of this component returning the following:

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

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

This produces the chart that is shown in the stackoverflow post that I linked.

推荐答案

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

For v3 you can use an method to set the tooltip programatically

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

这篇关于如何在图例悬停时显示工具提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆