Skip to content
索引

react中使用

安装

bash
npm i -s echarts
npm i -s echarts

使用

  1. 定义一个有宽高的html元素
  2. 获取那个有宽高的html元素,使用echarts的init方法初始化echarts
  3. 设置好echarts的option
  4. 使用init返回的echarts实例的setOption方法设置option

useRef绑定dom元素,使用useEffect生命周期c才能正确获取到dom元素

实例

ts
import { useRef, useEffect } from "react"
import styled from "styled-components"
import { init } from "echarts"
const option = {
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: "bar", 
      showBackground: true, 
      backgroundStyle: {
        color: "rgba(180, 180, 180, 0.2)"
      }
    }
  ]
}
function App() {
  const chartDom = useRef(null)
  useEffect(() => {
    const chart = init(chartDom.current as unknown as HTMLElement)
    chart.setOption(option)
  }, [])
  return (
    <>
      <StyleContainer>
        <div className="chart" ref={chartDom}></div>
      </StyleContainer>
    </>
  )
}
const StyleContainer = styled.section`
  .chart {
    width: 800px;
    height: 600px;
  }
`
export default App
import { useRef, useEffect } from "react"
import styled from "styled-components"
import { init } from "echarts"
const option = {
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: "bar", 
      showBackground: true, 
      backgroundStyle: {
        color: "rgba(180, 180, 180, 0.2)"
      }
    }
  ]
}
function App() {
  const chartDom = useRef(null)
  useEffect(() => {
    const chart = init(chartDom.current as unknown as HTMLElement)
    chart.setOption(option)
  }, [])
  return (
    <>
      <StyleContainer>
        <div className="chart" ref={chartDom}></div>
      </StyleContainer>
    </>
  )
}
const StyleContainer = styled.section`
  .chart {
    width: 800px;
    height: 600px;
  }
`
export default App

Released under the MIT License.