使用Recharts如何访问数据state字段为Bar组件设置条件属性
问题描述
我当前的BarChart配置如下:
<BarChart data={response} margin={{ top: 5, right: 40, bottom: 5, }} > <Legend /> <Tooltip offset={20} content={<LoadsBarChartTooltip />} /> <YAxis domain={[0, 'dataMax + 1']} label={{ value: 'Total Count', angle: -90, position: 'insideLeft', fontSize: '12px', }} /> <XAxis dataKey="trailer_id" tick={{ fontSize: 8 }} name="Trailer ID" /> <Bar stackId="a" dataKey="loaded_shipments" fill="#925abf" name="Loaded Shipments" /> <Bar stackId="a" dataKey="overage_shipments" fill="#A2BDF8" name="Overages" /> <Bar stackId="a" dataKey="shortaged_shipments" fill="#fdc6c6" name="Missing" /> </BarChart>
我清楚Recharts会自动将数据映射到Bar组件,但希望根据数据数组response中每个对象的state字段,为Bar设置stroke、strokeDasharray等样式属性,不确定该如何访问这个字段。
补充上下文:传入的数据类型定义如下:
export type GetLoadsRecievedWithAccuracyResponse = { trailer_id: string; accuracy: string; overage_shipments: string; loaded_shipments: string; shortaged_shipments: string; state: string; }[];
我已查阅相关资料但未找到答案,不确定是否可行。
解决方案
完全可以实现,Recharts的Bar组件支持通过两种方式访问单个数据项的完整信息(包括state字段),从而设置条件样式:
方法1:直接使用属性的函数形式
Recharts允许将stroke、strokeDasharray这类样式属性设置为函数,函数会接收当前数据项作为参数,你可以根据state的值返回对应的样式:
<Bar stackId="a" dataKey="loaded_shipments" fill="#925abf" name="Loaded Shipments" // 根据state设置边框颜色 stroke={(entry) => entry.state === '异常' ? '#ff0000' : '#000000'} // 根据state设置虚线样式 strokeDasharray={(entry) => entry.state === '待审核' ? '5 5' : '0'} strokeWidth={2} />
对另外两个Bar组件做同样的修改即可。
方法2:自定义cellRender实现复杂渲染
如果需要更灵活的自定义逻辑,可以使用cellRender属性,它会传入当前数据项的完整信息,你可以返回自定义的矩形元素:
<Bar stackId="a" dataKey="loaded_shipments" fill="#925abf" name="Loaded Shipments" cellRender={(props) => { const { x, y, width, height, fill, payload } = props; // payload即为当前数据项,包含state字段 const stroke = payload.state === '异常' ? '#ff0000' : '#000'; const strokeDasharray = payload.state === '待审核' ? '3 3' : ''; return ( <rect x={x} y={y} width={width} height={height} fill={fill} stroke={stroke} strokeDasharray={strokeDasharray} strokeWidth={2} /> ); }} />
注意:确保state字段的取值符合你的判断逻辑,避免出现样式不生效的情况。
内容的提问来源于stack exchange,提问作者astro20
相关产品推荐
相关产品推荐

