记录一下这个Echart的bug
链接:多个legend设置selected时,legend需要单击两次才能切换状态 · Issue #5391 · apache/echarts · GitHub
可以看到这是17年的bug,现在echart5.x都还存在 下面会给出bug的demo代码,触发条件和解决方法。
触发条件
1、设置了两条或者多条legend
2、bug仅存在于第一条legend之外
3、第二条或者N条legend设置了selected属性,且里面设置了false,为true不触发此bug
例如:legend[{...}, {...,selected: fasle}]
bug复现
可以去下方Echart的在线demo网站Examples - Apache ECharts 然后复制下方代码进去
option = {
tooltip: {
// show: true,
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {
color: 'red'
}
}
},
// grid: [
// {
// containLabel: true,
// // width: '70%'
// left: ''
// },
// ],
axisPointer: {
link: [
{
xAxisIndex: [0] // tooltip联动
}
]
},
toolbox: {
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
legend: [
{
data: ['Evaporation'],
selected: {
Evaporation: true,
},
},
{
data: ['Precipitation', 'Temperature'],
top: '10%',
selected: {
Precipitation: false,
Temperature: false,
},
}
],
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
],
yAxis: [
{
type: 'value',
name: 'Precipitation',
min: 0,
max: 250,
interval: 50,
axisLabel: {
formatter: '{value} ml'
}
},
{
type: 'value',
name: 'Temperature',
min: 0,
max: 25,
interval: 5,
axisLabel: {
formatter: '{value} °C'
}
}
],
series: [
{
name: 'Evaporation',
type: 'bar',
data: [
2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3
]
},
{
name: 'Precipitation',
type: 'bar',
data: [
2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3
]
},
{
name: 'Temperature',
type: 'line',
yAxisIndex: 1,
data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
}
]
};
可以看到下方的legend的首次点击无效,第二次点击才激活为true
解决方法
使用action.legend. legendUnSelect
取消选中图例。
dispatchAction({
type: 'legendUnSelect',
// 图例名称
name: string
})
echart初始化的时候,把全部legend设为false
示例代码
<MegaChart
getInstance={(inst) => {
option.legend[1]?.data.forEach((v) => {
inst.dispatchAction({
type: 'legendUnSelect',
// 图例名称
name: v,
});
});
}}
className="analyseEchart"
option={option}
style={{ height }}
/>