简体   繁体   English

React + Recharts 图例无法正常工作

[英]React + Recharts legend not working properly

I am using React + Recharts to create a stacked and grouped bar chart, it is my first time using Recharts.我正在使用 React + Recharts 创建一个堆叠和分组的条形图,这是我第一次使用 Recharts。 but the legend is not working properly, I want the legend to toggle both graphs in each group, but it is only working for the left side bar and not for the right side bar.但图例无法正常工作,我希望图例在每个组中切换两个图形,但它仅适用于左侧栏而不适用于右侧栏。 is it possible to make it work for both?是否有可能使它对两者都有效?

在此处输入图片说明

I did it like this:我是这样做的:

const selectBar = event => {
  let updatedLabels = [];
  let updatedLabelsSpend = [];
  for (let i = 0; i < data.labels.length; i++) {
    let label = data.labels[i];
    let spendLabel = data.filteredDataSpend[i];

    if (label.key !== event.value) {
      updatedLabels.push(label);
      updatedLabelsSpend.push(spendLabel);
    } else {
      if (/\s/.test(label.key) && /\s/.test(spendLabel.key)) {
        let newLabel = { key: label.key.trim(), color: label.color };
        let newLabelSpend = {
          key: spendLabel.key.trim(),
          color: spendLabel.color,
        };
        updatedLabels.push(newLabel);
        updatedLabelsSpend.push(newLabelSpend);
      } else {
        let newLabel = { key: label.key + ' ', color: label.color };
        let newLabelSpend = {
          key: spendLabel.key + ' ',
          color: spendLabel.color,
        };
        updatedLabels.push(newLabel);
        updatedLabelsSpend.push(newLabelSpend);
      }
    }
  }
  setData({ ...data, labels: updatedLabels });
};

you can check the demo in demo您可以在演示中查看演示

any help please?有什么帮助吗?

You were missing the state update for filteredDataSpend , this little change fix it你失踪了状态更新filteredDataSpend ,这种变化不大修复

    setData({
      ...data,
      labels: updatedLabels,
      filteredDataSpend: updatedLabelsSpend
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM