温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react+typescript中如何使用echarts

发布时间:2022-08-08 11:11:08 来源:亿速云 阅读:330 作者:iii 栏目:开发技术

这篇“react+typescript中如何使用echarts”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“react+typescript中如何使用echarts”文章吧。

安装echarts

npm install echarts --save

按需加载Echarts demo

echarts.init() API文档

import * as echarts from 'echarts/core'
import {
  BarChart,
  // 系列类型的定义后缀都为 SeriesOption
  LineChart,
} from 'echarts/charts'
import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  TooltipComponent,
  GridComponent,
  // 数据集组件
  DatasetComponent,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent,
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { useEffect, useRef } from 'react'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LineChart,
])

const ECharts: React.FC = () => {
  // 1. get DOM
  const chartRef = useRef(null)

  useEffect(() => {
    // 2. 实例化表格对象
    const chart = echarts.init(chartRef.current as unknown as HTMLDivElement, undefined, {
      width: 1000,
      height: 500,
    })
    // 3. 定义数据
    const option = {
      title: {
        text: '测试图表',
      },
      xAxis: {
        type: 'category',
        data: ['1-1', '1-2', '1-3', '1-5', '1-6', '1-7', '1-8', '1-9'],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: [140, 110, 100, 90, 70, 30, 10, 0],
          type: 'line',
        },
      ],
    }
    // 4. 调用表格数据
    chart.setOption(option)
  }, [])

  return <div className="charts" ref={chartRef} />
}

export default ECharts

错误记录

实例化Echarts的时候出现:“类型“null”的参数不能赋给类型“HTMLElement”的参数”错误,是typescript类型检查引起的,因此需要对该chartRef.current定义类型,可以定义成any,这里用的是typescript的双重断言去定义的类型。

发生错误的代码

react+typescript中如何使用echarts

修改后的代码

react+typescript中如何使用echarts

注意:

类型断言只能够「欺骗」TypeScript 编译器,无法避免运行时的错误,反而滥用类型断言可能会导致运行时错误 类型断言只会影响
TypeScript 编译时的类型,类型断言语句在编译结果中会被删除,所以它不是类型转换,不会真的影响到变量的类型。

将图表改为自适应容器大小 &ndash; .resize()

echarts中提供了resize函数能够自动改变图表的大小,但是需要使用window.onresize监听窗口的变化,只要窗口尺寸变化了就调用resize方法,并且图表的宽度和高度要分别设置成百分比和vh单位,否则resize会失效。

基于上面的demo实现
多复制一个表格数据之后在调用表格数据后面加window.resize函数,有多少个表就继续往后面加多少个resize。

 // 4. 调用表格数据
    chart.setOption(option)
    chart2.setOption(option2)
    // 5. 将图表变为自适应
    window.onresize = () => {
      chart.resize()
      chart2.resize()
    }

以上就是关于“react+typescript中如何使用echarts”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI