Recharts,在悬停时更改条形图中条形的背景颜色

问题描述

目前正在运行的图片

enter image description here

要求的图片

enter image description here

当前悬停图形时,颜色正在变化,但是当我悬停在条形图上方时,工具提示出现,但我的条形图未填充所选颜色。是他们在 recharts 中做到这一点的一种方式。 我正在添加一个易于理解的代码。提前致谢。

const [activeBarIndex,setActiveBarIndex] = useState();

<ResponsiveContainer width={"100%"} height={400}>
    <ComposedChart
      data={data}
      barCategoryGap={0}
      margin={{
        top: 20,right: 20,bottom: 20,left: 20,}}
    >
      <Cartesiangrid strokeOpacity={0} />
      <XAxis dataKey="name" hide />
      <YAxis hide />
      <Tooltip
        active={false}
        viewBox={{ x: 0,y: 0,width: 400,height: 400 }}
        content={<CustomTooltip />}
      />
      {trancheLines[selectedLine ? 0 : 1]}
      {trancheLines[!selectedLine ? 0 : 1]}
      <Bar
        size={20}
        dataKey="bargraph"
        onMouseEnter={(_,index) => setActiveBarIndex(index)}
        onMouseLeave={() => setActiveBarIndex()}
        isAnimationActive={false}
      >
        {data.map((entry,index) => (
          <Cell
            cursor="pointer"
            fill={index === activeBarIndex ? primaryColor : secondaryColor}
            key={entry.id}
          />
        ))}
      </Bar>
    </ComposedChart>
  </ResponsiveContainer>

解决方法

理论上答案是否定的,因为仅当 primaryColorCell 仅在 index === activeBarIndex 和 {{1 上设置时才会应用 activeBarIndexonMouseEnter }}。

实验方法(未测试):

让我们从以下事实开始:当您悬停某物时,会出现 onMouseLeave。好吧,所以我们可以使用这个事件来做一些事情。问题是,据我所知,Tooltip 没有任何 Tooltip 事件 (Tooltip API)。

我们唯一可以使用的是 onShow 属性。

好吧,如果您向工具提示添加引用:

active

您应该能够执行以下操作:

const toolRef = useRef();
...
<Tooltip
        ref={toolRef}
        active={false}
        viewBox={{ x: 0,y: 0,width: 400,height: 400 }}
        content={<CustomTooltip />}
      />
...

如果所有这些条件都为真,并且工具提示变为活动状态,则您可以设置 if(toolRef.current.active) //then the Tooltip is active 来解决您的问题。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...