Highcharts React

优质
小牛编辑
115浏览
2023-12-01

Highcharts React 是我们基于 React 框架封装的 Highcharts,可以很方便的在 React 开发环境中使用 Highcharts 创建交互性图表。

开发环境

确保您的 node, NPM, React 已经更新到最新版本。以下是经过测试和要求的版本:

  • node 8.11.3+
  • npm 6.4.1+ 或者类似的包管理工具
  • React 16.4+

Highcharts React 还需要您在项目中已经安装以下版本的 Highcharts:

  • highcharts 5.0.0+

安装

在您的 React 应用程序中通过 NPM 获取下载包:

npm install highcharts-react-official

如果您还没有安装 Highcharts 包,请一起获得:

npm install highcharts highcharts-react-official

使用

1. 基本用法示例

将 highcarts-react-official 导入到 React 项目中并渲染图表:

import React from 'react'
import { render } from 'react-dom'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

const options = {
    title: {
        text: 'My Chart'
    },
    seeries: [{
        data: [1, 2, 3]
    }]
}

const App = () => <div>
    <HighchartsReact 
        highcharts={Highcharts}
        options={options}
    />
</div>

render(<App />, document.getElementById('root'))

2. 使用 TypeScript 的 Highcharts

import * as React from 'react';
import * as ReactDom from 'react-dom';
import * as Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

// The wrapper exports only a default component class that at the same time is a
// namespace for the related Props interface (HighchartsReact.Props). All other
// interfaces like Options come from the Highcharts module itself.

const options: Highcharts.Options = {
    title: {
        text: 'My chart'
    },
    series: [{
        type: 'line',
        data: [1, 2, 3]
    }]
}

// React supports function components as a simple way to write components that
// only contain a render method without any state (the App component in this
// example).

const App = (props: HighchartsReact.Props) => <div>
    <HighchartsReact
        highcharts={Highcharts}
        options={options}
        {...props}
    />
</div>

// Render your App component into the #root element of the document.

ReactDom.render(<App />, document.getElementById('root'));

3. 使用 NextJS 的 Highcharts

Next.js 会在服务器端执行两次代码,然后再在客户端执行。首次运行时,因为缺少 window 导致加载了 Highcharts 但未进行初始化。比较简单的解决方法是将所有模块初始化放在一个 if 判断中,判断 Highcharts 是否是一个对象或一个函数。Highcharts 应该是正确的模块初始化中的一个对象,下面的代码是一个简单的解决方案:

import React from 'react'
import Highcharts from 'highcharts'
import HighchartsExporting from 'highcharts/modules/exporting'
import HighchartsReact from 'highcharts-react-official'

if (typeof Highcharts === 'object') {
    HighchartsExporting(Highcharts)
}

这是 NextJS 的一个已知问题,点击这里查看具体介绍

4. 推荐的更新图表方式

比较推荐的做法是将所有的图表配置选项保存在一个状态中。当 setState 被调用时,选项将被覆盖,只有新的配置选项被传递给 chart.update() 方法。

在线示例

import React, { Component } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

class LineChart extends Component {
constructor(props) {
    super(props);

    this.state = {
    // 为了避免不必要的更新,将所有图表配置选项保存起来
    chartOptions: {
        xAxis: {
        categories: ['A', 'B', 'C'],
        },
        series: [
        { data: [1, 2, 3] }
        ],
        plotOptions: {
        series: {
            point: {
            events: {
                mouseOver: this.setHoverData.bind(this)
            }
            }
        }
        }
    },
    hoverData: null
    };
}

setHoverData = (e) => {
    // 图表没有更新,因为 'chartOptions' 没有改变
    this.setState({ hoverData: e.target.category })
}

updateSeries = () => {
    // 图表只使用新配置选项进行更新
    this.setState({
    chartOptions: {
        series: [
        { data: [Math.random() * 5, 2, 1]}
        ]
    }
    });
}

render() {
    const { chartOptions, hoverData } = this.state;

    return (
    <div>
        <HighchartsReact
        highcharts={Highcharts}
        options={chartOptions}
        />
    <h3>Hovering over {hoverData}</h3>
    <button onClick={this.updateSeries.bind(this)}>Update Series</button>
    </div>
    )
}
}

render(<LineChart />, document.getElementById('root'));

选项具体配置

带有示例值的可用选项:

<HighchartsReact
    options = { this.state.chartOptions }
    highcharts = { Highcharts }
    constructorType = { 'mapChart' }
    allowChartUpdate = { true }
    immutable = { false }
    updateArgs = { [true, true, true] }
    containerProps = {{ className: 'chartContainer' }}
    callback = { this.chartCallback }
/>
.bold{font-weight:700}.center{text-align:center}.min-width-a{min-width:70px}.min-width-b{min-width:110px}
参数类型是否必需默认值描述
optionsObject-Highcharts 图表配置对象。详情请参照 Highcharts API 文档
highchartsObject-用于模块初始化后传递 Highcharts 实例。如果不设置,组件将尝试从 window 对象中获取 Highcharts
constructorTypeString'chart'构造函数方法的字符串。官方构造函数:
- 'chart' 用于 Highcharts 图表
- 'stockChart' 用于 Highstock 图表
- 'mapChart' 用于 Highmaps 图表
- 'ganttChart' 用于甘特图
allowChartUpdateBooleantrue在更改父组件时使用 chart.update( ) 方法将新选项应用于图表。此选项允许关闭更新。
immutableBooleanfalse在 prop 更新时重新初始化图表(与 chart.update( ) 相反)
- 在某些情况下有用,但比常规更新慢
updateArgsArray[true, true, true]数组 update( ) 的函数可选参数。参数应该以与原生 Highcharts 函数相同的顺序定义:[redraw, oneToOne, animation]。点击这里查看参数具体描述。
containerPropsObject-将 props 对象传递给 React.createElement( ) 方法中的图表容器。用于添加样式或类。
callbackFunction-创建图表后执行的回调函数。函数的第一个参数将保存创建的 chart 。函数中的 this 默认指向 chart 。此选项为可选

自定义图表组件的示例

  1. 创建自定义组件 ./components/MyStockChart.jsx

    import React from 'react'
    import Highcharts from 'highcharts/highstock'
    import HighchartsReact from 'highcharts-react-official'
    
    const options = {
        title: {
            text: 'My stock chart'
        },
        series: [{
            data: [1, 2, 3]
        }]
    }
    
    const MyStockChart = () => <HighchartsReact
        highcharts={Highcharts}
        constructorType={'stockChart'}
        options={options}
    />
    
    export default MyStockChart
    
  2. 渲染自定义图表组件,如下所示:

    import React from 'react'
    import { render } from 'react-dom'
    import MyStockChart from './components/MyStockChart.jsx'
    
    const App = () => <div>
        <MyStockChart />
    </div>
    
    render(<App />, document.getElementById('root'))
    

GitHub仓库

如果您需要,可以下载 github 仓库 并安装依赖项:

git clone https://github.com/highcharts/highcharts-react
cd highcharts-react
npm install

示例和测试都需要 Highcharts 库,请不要忘记安装:

npm install highcharts

演示示例

demo 文件夹中有一些实用的例子,它们使用了所有可用的构造函数和部分模块。

运行请输入以下语句:

npm run build-demo

演示 Demo 位于 demo/index.html 下

在线示例

测试

此插件包含以下测试:环境测试、图表渲染以及容器属性传递。如果您想运行测试,请输入以下语句:

npm run test

常见问题

1. 在哪里可以请求帮助?

技术支持将帮助您使用 Highcharts 和此插件。

如果您有需要报告的错误或建设性意见,请提交至 github 仓库

2. 为什么使用 highcharts-react-official 而不是 highcharts-react 作为名字?

在 NPM 包管理工具中 highcharts-react 已经被使用,所以注册为 highcharts-react-official

3. 如何获得图表实例?

方法一:使用 React.createRef()

componentDidMount() {
    this.chartRef = React.createRef();
}

render() {
    return (
        <HighchartsReact
        highcharts={ Highcharts }
        options={ options }
        ref={ this.chartRef }
        />
    );
}

方法二:使用回调函数存储

constructor(props) {
    super(props);
    this.afterChartCreated = this.afterChartCreated.bind(this);
}

afterChartCreated(chart) {
    this.internalChart = chart;
}

componentDidMount() {
    // 使用示例
    this.internalChart.addSeries({ data: [1, 2, 3] })
}

render() {
    return (
        <div>
        <h2>Highcharts</h2>
        <HighchartsReact
            highcharts={ Highcharts }
            options={ options }
            callback={ this.afterChartCreated }
        />
        </div>
    );
}

4. 如何添加其他模块?

如果您需要添加模块,以下提供了两种方法

方法一:将模块导入并初始化

// 导入模块
import Highcharts from 'highcharts'
import highchartsGantt from "highcharts/modules/gantt";
import HighchartsReact from 'highcharts-react-official'

// 初始化模块
highchartsGantt(Highcharts);

方法二:使用 require 方法

import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

require("highcharts/modules/variwide")(Highcharts);

5. 如何将 React 组件添加到图表元素中?

通过使用 Portals,可以向每个 HTML 图表元素添加组件。

在线示例