如何为SVG中的每个rect添加Material UI删除图标
解决方案
要给每个SVG矩形(rect)前置Material UI的Delete图标,可按以下步骤修改代码,确保每个图标与对应矩形绑定:
1. 确保图标已引入
import DeleteIcon from '@mui/icons-material/Delete';
2. React + D3 结合方案(适合React项目)
通过将Material UI图标转为SVG元素,插入到每个数据绑定的分组容器中:
import { useRef, useEffect } from 'react'; import * as d3 from 'd3'; import ReactDOMServer from 'react-dom/server'; import DeleteIcon from '@mui/icons-material/Delete'; function SvgLegend({ data }) { const svgRef = useRef(null); useEffect(() => { if (!data.length) return; const svg = d3.select(svgRef.current); const g = svg.append('g'); // 创建分组容器并绑定数据,控制每组水平间距 const legendGroups = g.selectAll('g.legendCells') .data(data) .enter() .append('g') .attr('transform', (_, i) => `translate(${i * 40}, 0)`); // 插入Delete图标到分组内 legendGroups.each(function() { const iconSvg = ReactDOMServer.renderToString( <DeleteIcon style={{ width: 20, height: 20, color: '#666' }} /> ); d3.select(this).html(iconSvg); }); // 添加矩形元素,放在图标右侧 legendGroups.append('rect') .attr('height', 20) .attr('width', 20) .style('fill', d => d.color) .attr('x', 25) // 图标与矩形的间距 .attr('y', 0); }, [data]); return <svg ref={svgRef}></svg>; }
3. 纯D3方案(不依赖React组件)
直接使用Delete图标的SVG路径数据创建图标元素:
function renderLegend(g, data) { // Material UI Delete图标的SVG路径 const deleteIconPath = "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"; // 创建分组容器 const legendGroups = g.selectAll("g.legendCells") .data(data) .enter() .append("g") .attr("transform", (_, i) => `translate(${i * 40}, 0)`); // 添加Delete图标 legendGroups.append("path") .attr("d", deleteIconPath) .style("fill", "#666") .attr("transform", "translate(0, 0)"); // 添加矩形元素 legendGroups.append("rect") .attr("height", 20) .attr("width", 20) .style("fill", d => d.color) .attr("x", 25) .attr("y", 0); }
关键说明
- 每个图标和矩形绑定在同一个
<g>分组中,通过transform或x属性控制位置,确保图标在矩形前方 - 可根据需求调整图标大小、颜色以及元素间的间距
- 原代码中重复调用
selectAll("rect")的逻辑已整合到创建步骤中,提升性能
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

