如何在 Highcharts 中使用 react 组件作为标签?

问题描述

我有一个 bubble map chart 可以在地图上显示城市的位置。地图具有标签,但我想在地图上使用 custom react component 作为 label。这是我的源代码,但它有错误并且不起作用:

import React,{ Component,Fragment } from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import HighchartsMap from "highcharts/modules/map";
import mapData from "@highcharts/map-collection/countries/gb/gb-all.geo.json";
import proj4 from "proj4";
import CustomLabel from "./CustomLabel";

HighchartsMap(Highcharts);

class BubbleMapChart extends Component {
  render() {
    const options = {
      chart: {
        map: "countries/gb/gb-all",proj4
      },series: [
        {
          name: "countries",nullColor: "#fff",showInLegend: false,mapData: mapData
        },{
          // Specify points using lat/lon
          type: "mapbubble",// PAY ATTENTION TO THIS SECTION - USE A CUSTOM LABEL COMPONENT
          dataLabels: {
            enabled: true,format: <CustomLabel name={"point.name"} />
          },minSize: "5%",maxSize: "15%",showInLegend: true,data: [
            {
              name: "London",lat: 51.507222,lon: -0.1275
            },{
              name: "Birmingham",lat: 52.483056,lon: -1.893611
            }
          ]
        }
      ]
    };

    return (
        <HighchartsReact
          highcharts={Highcharts}
          options={options}
          constructorType={"mapChart"}
        />
    );
  }
}

这是一个 customLabel 组件作为示例:

 import React,{ Component } from "react";
    class CustomLabel extends Component {
  render() {
    return (
      <div>
        {/* Doesn't show this Division (actually doesn't apply the style ...) */}
        <div
          style={{ BackgroundColor: "red",width: "10px",height: "10px" }}
        ></div>
        <span>{this.props.name}</span>

        <br />

        {/* Doesn't show the red bullet inside the text */}
        <Badge color="#f50" text={this.props.name} />
      </div>
    );
  }
}
    export default CustomLabel;

如何自定义 highcharts 中的数据标签?实际上我想使用自定义组件作为标签

解决方法

在数据标签的格式化函数中使用 ReactDOMServerrenderToStaticMarkuprenderToString 方法:

    dataLabels: {
      enabled: true,formatter: function () {
        return renderToStaticMarkup(<CustomLabel name={this.point.name} />);
      }
    }

现场演示: https://codesandbox.io/s/highcharts-react-demo-forked-40icn?file=/demo.jsx

文档: https://reactjs.org/docs/react-dom-server.html

API 参考: https://api.highcharts.com/highmaps/series.mapbubble.dataLabels.formatter


或者,如果您需要在 CustomLabel 中使用一些响应式逻辑,请利用 React 中的 Portal。


文档: https://reactjs.org/docs/portals.html

示例: https://www.npmjs.com/package/highcharts-react-official#how-to-add-react-component-to-a-charts-element