使用react-chartjs-2库自定义工具提示

时间:2017-06-29 00:28:12

标签: chart.js

我遇到了chartjs提供的默认工具提示问题,因为我无法在工具提示中添加html。我一直在研究如何在工具提示中添加html / jsx。我在此处看到了使用自定义工具提示的示例Chart JS Show HTML in Tooltip。 有人能给我一个例子,告诉我如何用react-chartjs-2库实现同样的目标吗?

3 个答案:

答案 0 :(得分:3)

您必须使用tooltip属性中的custom回调来定义自己的定位并将悬停数据集设置为组件状态

state = {
  top: 0,
  left: 0,
  date: '',
  value: 0,
};

_chartRef = React.createRef();

setPositionAndData = (top, left, date, value) => {
  this.setState({top, left, date, value});
};

render() {
  chartOptions = {
    "tooltips": {
      "enabled": false,
      "mode": "x",
      "intersect": false,
      "custom": (tooltipModel) => {
        // if chart is not defined, return early
        chart = this._chartRef.current;
        if (!chart) {
          return;
        }

        // hide the tooltip when chartjs determines you've hovered out
        if (tooltipModel.opacity === 0) {
          this.hide();
          return;
        }

        const position = chart.chartInstance.canvas.getBoundingClientRect();

        // assuming your tooltip is `position: fixed`
        // set position of tooltip
        const left = position.left + tooltipModel.caretX;
        const top = position.top + tooltipModel.caretY;

        // set values for display of data in the tooltip
        const date = tooltipModel.dataPoints[0].xLabel;
        const value = tooltipModel.dataPoints[0].yLabel;

        this.setPositionAndData({top, left, date, value});
      },
    }
  }

  return (
    <div>
      <Line data={data} options={chartOptions} ref={this._chartRef} />
      { this.state.showTooltip
        ? <Tooltip style={{top: this.state.top, left: this.state.left}}>
            <div>Date: {this.state.date}</div>
            <div>Value: {this.state.value}</div>
          </Tooltip>
        : null
      }
    </div>
  );
}

您可以使用React Popper Tooltip提供的工具提示或自己动手操作 - 将topleft传递到工具提示进行定位,date和{{1 (在我的例子中)应该用于显示工具提示中的数据。

答案 1 :(得分:0)

this.chart.chart_instance.canvas.getBoundingClientRect();

如果chart_instance出现错误,则应检查元素值的父级。

尝试一下:

this.chart.chartInstance.canvas.getBoundingClientRect();

答案 2 :(得分:-1)

记得在这里考虑React(这并不总是那么容易)。使用mycustomtooltipfunction在React类中设置状态(具体来说,将传递给mycustometooltipfunction的工具提示添加到状态 - 这将导致render被调用。现在在{{ 1}}类的功能,检查该状态是否存在,并为工具提示添加JSX。

render

`

相关问题