如何使用图表工具提示格式化程序? 我正在使用反应包装进行高级图表 我有这样的配置:
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
},
...
}
但是我无法使用此关键字访问图表范围,也无法从工具提示参数获取点。 感谢
答案 0 :(得分:4)
我已经遇到过这个问题。我通过创建一个格式化工具提示的函数,并将默认值应用于我想要的数据来解决它。
以下是a live example,代码如下:
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'));
答案 1 :(得分:2)
这是另一种方法,它也可以帮助您将React组件用作工具提示本身的一部分。
const Item = ({name, value}) => <div> {name}: {value}</div>
const config = {
formatter(this) {
const container = document.createElement("div");
return this.points.map(point => {
ReactDOM.render(
<Item name={point.series.name} value={point.y}/>
)
return container.innerHTML
}
}
}
答案 2 :(得分:0)
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
},
...
}
答案 3 :(得分:0)
Highcharts 预计 tootlip fromatter 将返回一个 HTML 字符串。当为 Highcharts 使用 react 包装器时,可以使用格式化数据编写自定义工具提示组件,然后在设置格式化程序功能时的选项中,您可以使用 ReactDOMServer's renderToString
方法来创建 HTML来自给定元素的字符串。
虽然 renderToString 主要用于服务器端渲染,但它可以毫无问题地用于浏览器环境。
import ReactDOMServer from 'react-dom/server';
import CustomTooltip from './CustomTooltip';
const options = {
tooltip: {
formatter() {
return ReactDOMServer.renderToString(<CustomTooltip {...this} />);
},
},
};
答案 4 :(得分:-1)
我创建了一个工具提示切换器,可以用作常规工具提示或共享。
isTooltipShared
是一个布尔型道具,指示是否共享工具提示。
const options = {
tooltip: {
formatter: props.isTooltipShared ?
function () {
let s = `<b> ${this.x} </b>`;
this.points.forEach((point) => {
s += `<br/> ${point.series.name} : ${point.y}`;
});
return s;
} : function () {
return `${this.series.name} : <b> ${this.x} </b> - <b> ${this.y} </b>`;
},
shared: props.isTooltipShared,
},
};
并与
一起使用<HighchartsReact
highcharts={Highcharts}
options={options}
/>