关于react.js:ECharts封装成React组件

3次阅读

共计 1982 个字符,预计需要花费 5 分钟才能阅读完成。

tsxecharts

https://github.com/lloydzhou/…

React component wrapper for ECharts based on TypeScript.

我的项目设计

  1. 参考 vuecharts3 对 echarts 进行封装
  2. 将 echarts 官网形象的 series 以及其余的一些组件形象成为 React 的组件应用,每一个组件负责管理本人的配置项。
  3. 这些配置项对立的合并到 Chart 画布组件。再对立的通过 chart.setOption 更新到图表上

装置

yarn add tsxecharts

Components

  1. 定义一个 Chart 组件作为画布
  2. 将 echarts 官网配置项每一个配置项应用对立的工厂函数结构成React Component

DEMO

import 'echarts'
import Echarts from 'vuecharts3'
import {Chart, Line, Bar, Title, Grid, XAxis, YAxis, Tooltip} from 'tsxecharts'

function App() {

  return (
    <div className="App">
      <Chart width={800}>
        <Grid top={100} />
        <Title text="顶部题目" subtext="顶部小标题" left="center" top={10} />
        <Title text="底部题目" top="bottom" left="center" />
        <Bar name="data1" data={[0.32, 0.45, 0.2]} />
        <Bar name="data2" data={[0.2, 0.5, 0.3]} />
        <Line name="data2" data={[0.2, 0.5, 0.3]} />
        <XAxis data={['x1', 'x2', 'x3']} />
        <YAxis />
        <Tooltip trigger="axis" />
      </Chart>
    </div>
  )
}

自定义组件

  1. 通过自定义组件实现官网切换图像的 example
function TreemapSunburstTransition() {const [type, setType] = useState('')
  const [data, setData] = useState()
  const interval = useRef()
  const id = 'echarts-package-size'

  useEffect(() => {const url = "https://fastly.jsdelivr.net/gh/apache/[email protected]/examples/data/asset/data/echarts-package-size.json"
    fetch(url).then(res => res.json()).then(data => {setData(data.children)
      let type = ''console.log('data.value', data.children)
      interval.current && clearInterval(interval.current);
      // @ts-ignore
      interval.current = setInterval(function () {setType(type = type === 'treemap' ? 'sunburst' : 'treemap')
        console.log('state.type', type)
      }, 3000);
    })
    return () => interval.current && clearInterval(interval.current)
  }, [])

  if (type === 'treemap') {return <Treemap id={id} animationDurationUpdate={1000} roam={false} nodeClick={undefined} data={data} universalTransition label={{show: true}} breadcrumb={{show: false}} />
  }
  return <Sunburst id={id} radius={['20%', '90%']} animationDurationUpdate={1000} nodeClick={undefined} data={data} universalTransition label={{show: false}} itemStyle={{borderWidth: 1, borderColor: 'rgba(255,255,255,.5)'}} />
}


function App() {

  return (
    <div className="App">
      <Chart width={800}>
        <TreemapSunburstTransition />
      </Chart>
    </div>
  )
}

正文完
 0