react+typescript中使用echarts的實現(xiàn)步驟
npm install echarts --save
按需加載Echarts demo
import * as echarts from 'echarts/core' import { BarChart, // 系列類型的定義后綴都為 SeriesOption LineChart, } from 'echarts/charts' import { TitleComponent, // 組件類型的定義后綴都為 ComponentOption TooltipComponent, GridComponent, // 數(shù)據(jù)集組件 DatasetComponent, // 內(nèi)置數(shù)據(jù)轉(zhuǎn)換器組件 (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. 定義數(shù)據(jù) 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. 調(diào)用表格數(shù)據(jù) chart.setOption(option) }, []) return <div className="charts" ref={chartRef} /> } export default ECharts
錯誤記錄
實例化Echarts的時候出現(xiàn):“類型“null”的參數(shù)不能賦給類型“HTMLElement”的參數(shù)”錯誤,是typescript類型檢查
引起的,因此需要對該chartRef.current
定義類型,可以定義成any
,這里用的是typescript的雙重斷言去定義的類型。
發(fā)生錯誤的代碼
修改后的代碼
注意:
類型斷言只能夠「欺騙」TypeScript 編譯器,無法避免運行時的錯誤,反而濫用類型斷言可能會導(dǎo)致運行時錯誤 類型斷言只會影響
TypeScript 編譯時的類型,類型斷言語句在編譯結(jié)果中會被刪除,所以它不是類型轉(zhuǎn)換,不會真的影響到變量的類型。
將圖表改為自適應(yīng)容器大小 – .resize()
echarts中提供了resize函數(shù)能夠自動改變圖表的大小,但是需要使用window.onresize
去監(jiān)聽窗口
的變化,只要窗口尺寸變化了就調(diào)用resize方法,并且圖表的寬度和高度要分別設(shè)置成百分比和vh單位
,否則resize會失效。
基于上面的demo實現(xiàn):
多復(fù)制一個表格數(shù)據(jù)之后在調(diào)用表格數(shù)據(jù)后面加window.resize函數(shù),有多少個表就繼續(xù)往后面加多少個resize。
// 4. 調(diào)用表格數(shù)據(jù) chart.setOption(option) chart2.setOption(option2) // 5. 將圖表變?yōu)樽赃m應(yīng) window.onresize = () => { chart.resize() chart2.resize() }
到此這篇關(guān)于react+typescript中使用echarts的實現(xiàn)步驟的文章就介紹到這了,更多相關(guān)react typescript中使用echarts內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
webpack4 + react 搭建多頁面應(yīng)用示例
這篇文章主要介紹了webpack4 + react 搭建多頁面應(yīng)用示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08react同構(gòu)實踐之實現(xiàn)自己的同構(gòu)模板
這篇文章主要介紹了react同構(gòu)實踐之實現(xiàn)自己的同構(gòu)模板,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03