如何在react-highcharts中使用图表工具提示格式化程序?

kra*_*one 8 javascript highcharts reactjs react-redux react-highcharts

我该如何使用图表工具提示格式化程序?我正在使用反应包装器来进行高级图表.
我有这样的配置:

const CHART_CONFIG = {
    ...
    tooltip:  
    {
        formatter: (tooltip) => {
            var s = '<b>' + this.x + '</b>';
            _.each(this.points, () => {
                s += '<br/>' + this.series.name + ': ' + this.y + 'm';
            });
            return s;
        },
        shared: true
    },
    ...
}    
Run Code Online (Sandbox Code Playgroud)

但我无法使用此关键字访问图表范围,也无法从工具提示参数中获取信息.谢谢

Phi*_*ley 7

OP 无法弄清楚如何使用this关键字访问图表的范围。简单的答案是因为 OP 使用了一个胖箭头函数。相反,请尝试根据 OP 代码的此修改版本使用普通函数:

const CHART_CONFIG = {
    ...
    tooltip:  
    {
        formatter() {   // Use a normal fn, not a fat arrow fn
            // Access properties using `this`
            // Return HTML string
        },
        shared: true
    },
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这是因为箭头函数失去了“this”的踪迹,我们必须使用普通函数:)谢谢 (3认同)

Adr*_*oix 6

我已经遇到了这个问题。我已经解决了这一问题,方法是创建一个函数来格式化工具提示,然后将默认值应用于所需的数据。

这是一个实时示例,代码如下:

import React, { Component } from 'react';
import { render } from 'react-dom';
import ReactHighcharts from 'react-highcharts';
import './style.css';

class App extends Component {
  static formatTooltip(tooltip, x = this.x, points = this.points) {
    let s = `<b>${x}</b>`;
    points.forEach((point) =>
      s += `<br/>${point.series.name}: ${point.y}m`
    );

    return s;
  }

  static getConfig = () => ({
    xAxis: {
      categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    tooltip: {
      formatter: App.formatTooltip,
      shared: true,
    },
    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]
    }, {
        data: [194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4]
    }],
  })

  render() {
    return (
      <div>
        <ReactHighcharts config={App.getConfig())} />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)