共计 8202 个字符,预计需要花费 21 分钟才能阅读完成。
本文完整版:《React Echarts 应用教程 – 如何在 React 中退出图表(内附数据看板实战搭建案例)》
Ehcarts 作为数据展现的组件,利用场景丰盛,所以在 React 里引入 Echarts 图表是每个前端必会技能。而 Echarts
配置项多且简单,每个配置项都会细分很多个配置小项,并且还对外裸露了一套 API,包含图表实例,事件监听等,还是有肯定的上手难度。
本文手把手教大家如何在 React
里应用 Echarts
,并结合实际应用场景,分享我是如何解决图表自适应等具体问题。最初来一个实战教学,教大家如何联合 ant-design React UI 框架,开发企业级的「数字币走势数据看板」,帮忙大家加深对 Echarts
的了解。
当然,如果你基本不想解决任何前端问题,就想专一在产品开发上,那么举荐应用卡拉云,卡拉云是新一代低代码开发工具,内置包含 Ehcarts 在内的多种常见的前端组件,拖拽即可生成,还可一键接入常见数据库及 API,无需懂前端,疾速搭建属于你本人的后盾管理工具,一周工作量缩减至 1 天,详见本文文末。
如何在 React 里引入 Echarts
首先,咱们须要初始化 React
我的项目,这里应用 create-react-app
即可轻松实现,以下两个命令都能够,是等价的:
yarn create react-app kalacloud-react-echarts | |
// OR | |
create-react-app kalacloud-react-echarts |
初始化胜利后,咱们就能够在我的项目中装置 Echarts
,这里咱们应用 Echarts
的最新版本:
装置好 Echarts
之后,咱们就能够在我的项目中引入应用了。Echarts
反对两种引入形式:
- 全量引入
import * as echarts from 'echarts';
- 按需引入
// 引入 echarts 外围模块 | |
import * as echarts from 'echarts/core'; | |
// 按需引入图表类型 | |
import {BarChart} from 'echarts/charts'; | |
// 按需引入题目,提示框组件 | |
import {TitleComponent, TooltipComponent} from 'echarts/components'; | |
// 引入 Canvas 渲染器 | |
import {CanvasRenderer} from 'echarts/renderers'; | |
// 注册必须的组件 | |
echarts.use([ | |
BarChart, | |
TitleComponent, | |
TooltipComponent, | |
CanvasRenderer | |
]); | |
// 接下来的应用就跟之前一样,初始化图表,设置配置项 | |
var myChart = echarts.init(document.getElementById('main')); | |
myChart.setOption({// ...}); |
这里为了简略起见,咱们间接应用全局引入的形式即可。引入 echarts
后,咱们先来实现一个折线 + 柱状图。
扩大浏览:《7 款最棒的开源 React 挪动端 UI 组件库和模版框架》
React Echarts 实现折线图 + 柱状图
在 src 目录下,新建一个 components 文件夹,用来寄存咱们的图表组件,而后新建一个 LineBarChart.js,用来展示折线柱状图组件:
地位:src/components/LineBarChart.js
import {useEffect, useRef} from "react"; | |
import * as echarts from "echarts"; | |
function LineBarChart() {const chartRef = useRef(null); | |
useEffect(() => {let chartInstance = echarts.init(chartRef.current); | |
const option = { | |
legend: { | |
data: [ | |
"3-11 岁工作数", | |
"3-11 岁全程接种量", | |
"60 岁工作数", | |
"60 岁全程接种量", | |
"80 岁工作数", | |
"80 岁全程接种量", | |
"完成率", | |
], | |
}, | |
xAxis: { | |
type: "category", | |
data: ["街道 1", "街道 2", "街道 3", "街道 4", "街道 5", "街道 6", "街道 7"], | |
}, | |
yAxis: [{ type: "value"}, | |
{ | |
type: "value", | |
name: "%", | |
nameTextStyle: { | |
color: "#ccc", | |
padding: [0, 0, 10, -30], | |
}, | |
splitNumber: 5, | |
splitLine: { | |
show: true, | |
lineStyle: { | |
type: "dashed", | |
width: 1, | |
color: ["#ccc", "#ccc"], | |
}, | |
}, | |
axisLabel: { | |
show: true, | |
textStyle: {fontSize: 12,}, | |
}, | |
}, | |
], | |
tooltip: { | |
trigger: "axis", | |
axisPointer: {type: "shadow",}, | |
textStyle: { | |
color: "#fff", | |
align: "left", | |
fontSize: 14, | |
}, | |
backgroundColor: "rgba(0,0,0,0.8)", | |
}, | |
series: [ | |
{ | |
name: "3-11 岁工作数", | |
data: [150, 230, 224, 218, 135, 147, 260], | |
type: "bar", | |
}, | |
{ | |
name: "3-11 岁全程接种量", | |
data: [150, 230, 224, 218, 135, 147, 260], | |
type: "bar", | |
}, | |
{ | |
name: "60 岁工作数", | |
data: [150, 230, 224, 218, 135, 147, 260], | |
type: "bar", | |
}, | |
{ | |
name: "60 岁全程接种量", | |
data: [880, 30, 124, 118, 35, 47, 160], | |
type: "bar", | |
}, | |
{ | |
name: "80 岁工作数", | |
data: [660, 30, 124, 118, 35, 47, 160], | |
type: "bar", | |
}, | |
{ | |
name: "80 岁全程接种量", | |
data: [880, 30, 124, 118, 35, 47, 160], | |
type: "bar", | |
}, | |
{ | |
name: "完成率", | |
data: [50, 130, 124, 18, 35, 47, 160], | |
yAxisIndex: 1, | |
type: "line", | |
smooth: true, | |
}, | |
], | |
}; | |
chartInstance.setOption(option); | |
}, []); | |
return (<div style={{ textAlign: "center"}}> | |
<h2>React Echarts 折线 + 柱状图 </h2> | |
<div ref={chartRef} style={{height: "400px"}}></div> | |
</div> | |
); | |
} | |
export default LineBarChart; |
成果如下:
当然,如果你齐全不想解决前端问题,间接在卡拉云拖拽一个图表组件,而后把 Echarts 代码间接贴进去就能生成图表。
当然,你也能够把做好的图表一键分享给共事应用,或嵌入在你本人的网页里,像上面这样。
以上就能够联合 React
,就能够实现一个简略的折线图、柱状图。理解更多折线图、柱状图等可看咱们的 Echart 系列教程。
- Echarts 折线图齐全配置指南
- Echarts 折线图、柱状图、饼图多种渐变色设置指南
- Echarts 关系图齐全配置指南
- 如何设置 Echarts 标线(markLine)及平均值、最大最小值及色彩
- ECharts 饼图色彩设置教程
在本教程中,我挑两个重点讲一下,着重讲讲 series
,xAxis
这两个属性配置,series 示意一个系列的数据,type 示意系列类型;xAxis 示意 x 轴的数据。它们是一个数组,必须保持数据的有序性和一一对应,否则会呈现数据错乱。Echart
的的次要 API
就是 setOption
,咱们能够利用这个,封装一个通用的图表组件,还能够对立解决自适应,容错等问题。
扩大浏览:《最好的 6 个 React Table 组件具体亲测举荐》
React Echarts 封装通用图表组件
在 components 文件夹下新建 Chart.js
文件:
import {useEffect, useRef} from "react"; | |
import * as echarts from "echarts"; | |
function Chart({options}) {const chartRef = useRef(null); | |
let chartInstance = null; | |
// 定义渲染函数 | |
function renderChart() { | |
try { | |
// `echarts.getInstanceByDom` 能够从曾经渲染胜利的图表中获取实例,其目标就是在 options 产生扭转的时候,不须要 | |
// 从新创立图表,而是复用该图表实例,晋升性能 | |
const renderedInstance = echarts.getInstanceByDom(chartRef.current); | |
if (renderedInstance) {chartInstance = renderedInstance;} else {chartInstance = echarts.init(chartRef.current); | |
} | |
chartInstance.setOption(options); | |
} catch (error) {console.error("error", error.message); | |
chartInstance && chartInstance.dispose();} | |
} | |
// 定义窗口大小产生扭转执行的回调函数 | |
function resizeHandler() {chartInstance.resize(); | |
} | |
// 页面初始化时,开始渲染图表 | |
useEffect(() => {renderChart(); | |
return () => { | |
// 销毁图表实例,开释内存 | |
chartInstance && chartInstance.dispose();}; | |
}, []); | |
// 监听窗口大小扭转 | |
useEffect(() => {window.addEventListener("resize", resizeHandler); | |
return () => window.removeEventListener("resize", resizeHandler); | |
}, []); | |
return ( | |
<div> | |
<h2> 折线 + 柱状图 </h2> | |
<div style={{height: "400px"}} ref={chartRef} /> | |
</div> | |
); | |
} | |
export default Chart; |
我在代码里做了具体的正文,不便大家了解。以上就实现了一个通用的图表组件,只须要传入 options
即可,咱们来应用以下这个组件,批改 App.js
如下:
import Chart from "./compoennts/Chart"; | |
const options = {tooltip: {}, | |
legend: {data: ["销量"], | |
}, | |
xAxis: {data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], | |
}, | |
yAxis: {}, | |
series: [ | |
{ | |
name: "销量", | |
type: "bar", | |
data: [5, 20, 36, 10, 10, 20], | |
}, | |
], | |
}; | |
function App() { | |
return ( | |
<div className="App"> | |
<Chart options={options} /> | |
</div> | |
); | |
} | |
export default App; |
简单明了,成果如下:
封装通用组件的益处就是能够让咱们更关注业务实现,不须要去关怀底层图表具体的实现形式,前面我会给大家介绍如何应用卡拉云搭建图表零碎,让咱们只关注业务层,无需关怀代码实现。
扩大浏览:《最好用的 5 款 React 富文本编辑器》
基于 Ant Design React 搭建数字币走势数据看板
本节咱们应用国内最罕用的 React UI 框架 Ant Design React 来手把手教大家搭一套极简版数字币走势数据看板,帮忙大家加深了解 Echarts
。首先,咱们须要装置 antd
作为我的项目的 UI
框架,而后还须要装置 axios
来发送申请获取数据,还须要 dayjs
不便咱们解决日期:
yarn add antd axios dayjs
装置胜利后,在 index.js
导入 antd
的 款式文件
import "antd/dist/antd.min.css"
接下来就能够正式进入开发了,首先阐明下咱们要做的事件:
- 封装工具类,用来解决公共申请,日期等场景
- 实现一个趋势图组件,用来显示币种的价格走势
第一步,先封装一个工具类,在 src
目录下新建 utils
文件夹,而后新建 request.js
文件,用来解决申请发送:
import axios from "axios"; | |
const apiKey = "B8XHZFRRAIWTAMDHZXWSNHB0IHVT1HGF7JS6DPHA"; | |
export const request = axios.create({ | |
baseURL: "https://data.mifengcha.com", | |
headers: {"X-API-KEY": apiKey}, | |
}); |
这里是我申请的 API key
,大家间接应用就能够了,不是文章的重点。接着咱们再新建一个文件 days.js
,用来解决日期范畴相干的逻辑:
import dayjs from "dayjs"; | |
export const getTimestamp = (day) => {return dayjs().subtract(day, "day").valueOf();}; | |
export const getDates = (day) => {return new Array(day) | |
.fill(0) | |
.map((d, index) => dayjs().subtract(index, "day").format("YYYY-MM-DD")); | |
}; |
把下面的代码间接粘贴即可。而后咱们还须要发送申请,所以在 src
目录下 新建 service
文件夹,新建一个 chartAPI.js
,对立寄存咱们要发送的申请 url:
import {request} from "../utils/request"; | |
export const getData = (params) => {return request.get("/api/v3/price/history", { params}); | |
}; |
创立完之后,就能够开始编写真正的渲染组件了,还记得第一节封装的通用图表组件吗,当初咱们就能够间接应用这个组件了,在 components
下创立趋势图组件 LineBarChart.js
,用来展现单个趋势图:
import Chart from "./Chart"; | |
import {getData} from "../service/chartAPI"; | |
import {getTimestamp, getDates} from "../utils/days"; | |
import {useEffect, useState} from "react"; | |
import {Spin} from "antd"; | |
function getOptions(xAxisData, seriesData) { | |
return { | |
xAxis: { | |
type: "category", | |
data: xAxisData, | |
}, | |
yAxis: {type: "value",}, | |
tooltip: {trigger: "axis",}, | |
grid: { | |
top: 40, | |
left: 40, | |
bottom: 40, | |
right: 40, | |
containLabel: true, | |
}, | |
series: [ | |
{ | |
data: seriesData, | |
type: "line", | |
smooth: true, | |
}, | |
], | |
}; | |
} | |
function BitcoinTrendChart({slug, day = 7}) {const [options, setOptions] = useState({}); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => {setLoading(true); | |
getData({ | |
slug, | |
start: getTimestamp(day), | |
interval: "1d", | |
}).then((res) => {const seriesData = res.data.map((item) => item.u); | |
const xAxisData = getDates(day); | |
setOptions(getOptions(xAxisData, seriesData)); | |
setLoading(false); | |
}); | |
}, [slug, day]); | |
return (<Spin spinning={loading}> | |
<Chart options={options} /> | |
</Spin> | |
); | |
} | |
export default BitcoinTrendChart; |
以上代码编写实现后,还有最初一步,就是应用这个趋势图组件,批改 App.js
如下:
import {Row, Col, Select, Form} from "antd"; | |
import {useState} from "react"; | |
import TrendChart from "./compoennts/TrendChart"; | |
const {Option} = Select; | |
const layout = {labelCol: { span: 8}, | |
wrapperCol: {span: 16}, | |
style: {width: "400px"}, | |
}; | |
function App() {const [day, setDay] = useState(7); | |
return ( | |
<div className="App"> | |
<h2> 数字币走势数据看板 </h2> | |
<Form {...layout}> | |
<Form.Item label="周期"> | |
<Select defaultValue={7} onChange={setDay}> | |
<Option value={7}>7 天 </Option> | |
<Option value={30}>30 天 </Option> | |
</Select> | |
</Form.Item> | |
</Form> | |
<Row> | |
<Col span={12}> | |
<h3> 比特币 </h3> | |
<TrendChart slug="bitcoin" day={day} /> | |
</Col> | |
<Col span={12}> | |
<h3> 狗币 </h3> | |
<TrendChart slug="dogecoin" day={day} /> | |
</Col> | |
<Col span={12}> | |
<h3> 以太坊 </h3> | |
<TrendChart slug="ethereum" day={day} /> | |
</Col> | |
<Col span={12}> | |
<h3> 币安币 </h3> | |
<TrendChart slug="binance-coin" day={day} /> | |
</Col> | |
</Row> | |
</div> | |
); | |
} | |
export default App; |
而后关上浏览器 http://localhost:3000,就能够看到最终成果了:
本文所有代码均在 github 能够找到。
扩大浏览:《React form 表单验证终极教程》
React Echarts 与卡拉云
本文具体解说新版 React 中如何引入 Echarts。其实如果你基本不想解决简单的前端问题,齐全能够应用卡拉云来搭建数据看板,卡拉云内置包含 Echarts 在内的多种罕用组件,无需懂任何前端,仅需拖拽即可疾速生成,一键连贯后端数据源,极速开发后盾管理工具。
卡拉云可帮你疾速搭建企业外部工具,下图为应用卡拉云搭建的外部广告投放监测零碎,无需懂前端,仅需拖拽组件,10 分钟搞定。你也能够疾速搭建一套属于你的后盾管理工具,理解更多。
卡拉云是新一代低代码开发平台,与前端框架 Vue、React 等相比,卡拉云的劣势在于不必首先搭建开发环境,间接注册即可开始应用。开发者齐全不必解决任何前端问题,只需简略拖拽,即可疾速生成所需组件,可一键接入常见数据库及 API,依据疏导简略几步买通前后端,数周的开发工夫,缩短至 1 小时。立刻收费试用卡拉云。
扩大浏览:
- 最好用的 8 款 React Datepicker 工夫日期选择器测评举荐
- React Router 6 (React 路由) 最具体教程
- React Draggable 实现拖拽 – 最具体中文教程
- 最好的 6 款 React admin 后盾管理系统模板和框架