【问题标题】:Recharts Event not working when bar chart bar value is 0当条形图条值为 0 时,Recharts 事件不起作用
【发布时间】:2018-06-22 06:51:10
【问题描述】:

我正在使用 Recharts BarChart 组件来可视化我的数据。在Bar component 中,它支持一些事件处理程序(onClick、onMouseDown 等)。

我的问题:我有一个 onClick 事件处理程序,因此用户可以单击条形图并根据结果 ID 重定向到其他页面。

我的问题:如果条形图的值为 0,则用户无法点击链接,因为 onClick 事件处理程序是在条形本身上实现的。

源代码

<BarChart
  width={500}
  height={500}
  layout="vertical"
  data={data}
>
  <XAxis type="number" />
  <YAxis dataKey="title" type="category" />
  <Bar
    dataKey="score"
    fill={Color}
    label={<CustomLabel />}
    onClick={(data, index) => {
      // some logic here
      return history.push(`/${data.x.y.id}`);
    }}
  />
</BarChart>

截图

我的尝试

我试图查看一个可能的解决方案并观察 recharts 网站中 API 上的示例,但我没有看到任何能够解决我的问题的方法。我还尝试在轴或栏上的标题上单击 onClick,但该组件不支持该功能。请指教。

【问题讨论】:

    标签: reactjs recharts


    【解决方案1】:

    您可以在BarChart 组件上添加onClick 属性并检查data.activePayload[0] 以查看单击了哪个条形图。

    <BarChart
      width={500}
      height={500}
      layout="vertical"
      data={data}
      onClick={(data) => {
        // do your history.push based on data.activePayload[0]
        if (data && data.activePayload && data.activePayload.length > 0) {
          return history.push(`/${data.activePayload[0].x.y.id}`);
        }
      }}
    >
      <XAxis type="number" />
      <YAxis dataKey="title" type="category" />
      <Bar
        dataKey="score"
        fill={Color}
        label={<CustomLabel />}
      />
    </BarChart>
    

    【讨论】:

    • 当点击轴的标题时,条件if (data.activePayload.length &gt; 0) 将不起作用,因为数据是null。请改用if (data)
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多