反応+タイプスクリプトでのechartの使用

Echart をインストールする

npm install echarts --save

Echarts デモをオンデマンドでロード

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 をインスタンス化すると「A parameter of type "null" cannot be assigned to a parameter of type "HTMLElement"」エラーが発生するため、ここでtypescript のdouble assertionとして定義できる型を定義するtypescript类型检查必要があります。定義された型に移動するために使用されますchartRef.currentany

エラーコード

ここに画像の説明を挿入

変更されたコード

ここに画像の説明を挿入

知らせ:

Type assertions can only "cheat" the TypeScript compiler, and can not avoid runtime errors. 反対に、型アサーションの誤用は実行時エラーを引き起こす可能性があります. 型アサーションは、TypeScript がコンパイルされたときにのみ型に影響を与えます
.コンパイル結果なので、型変換ではなく、変数の型には実際には影響しません。

チャートをアダプティブ コンテナー サイズに変更する –.resize()

echarts で提供されている resize 関数は、チャートのサイズを自動的に変更できますが、ウィンドウ サイズが変更され、 resize メソッドが呼び出され、 chart が変更される限り、これを使用してチャートのサイズをwindow.onresize変更する必要があります。それ以外の場合、サイズ変更は無効になります。监听窗口宽度和高度要分别设置成百分比和vh单位

上記のデモの実装に基づいて:
テーブル データをもう 1 つコピーした後、テーブル データを呼び出した後に window.resize 関数を追加します。,有多少个表就继续往后面加多少个resize。

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

おすすめ

転載: blog.csdn.net/weixin_46353030/article/details/126121705