React 我想在 react-chart-2 工具提示中添加文本

React I want to add text to the react-chart-2 tooltip

我正在使用 react-chart-2。
将鼠标悬停在图表上以查看工具提示。我想在数字的右边显示一个 %,比如 30%。
如何将 % 字符添加到工具提示?另外,如何设置左边的值最小为0,最大为100?

code

import "./styles.css";
import { Line } from "react-chartjs-2";

const App = () => {
  const data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
      {
        label: "test",
        data: [30, 10, 10, 40, 70, 10, 30],
        fill: false,
        backgroundColor: "#F7C520",
        borderColor: "#F7C520",
        hoverBackgroundColor: "#E6B71E",
        hoverBorderColor: "#E6B71E"
      }
    ]
  };

  const options = {
    responsive: true,
    tooltips: {
      mode: "label"
    },
    elements: {
      line: {
        fill: false
      }
    },
    scales: {
      xAxes: [
        {
          display: true,
          gridLines: {
            display: true
          }
        }
      ]
    }
  };

  return (
    <div className="App">
      <h2>Mixed data Example</h2>
      <Line data={data} options={options} />
    </div>
  );
};

export default App;

ChartJS 提供了一个回调,让您可以 customize the contents of your tooltip. ChartJS also has many other Tooltip callbacks 方便地自定义图表的外观,而 react-chartjs-2 作为 ChartJS 的包装器,允许相同的功能。

添加一个 plugins 包含工具提示配置的对象,如下所示:

    plugins: {
      tooltip: {
        callbacks: {
          label: (context: any) => {
            let label = "";
            if (context.parsed.y) {
              label = context.parsed.y + "%"
            }
            return label;
          }
        }
      }
    }

导致:

至于你的另一个问题,你似乎已经在沙盒中解决了。将轴上的 minmax 值设置为所需值。