React-D3-Tree 3.5.1自定义节点阴影不生效问题排查与解决建议
React-D3-Tree自定义矩形节点添加阴影的解决方案
SVG的<rect>元素不支持CSS的box-shadow属性,这就是你当前阴影效果不生效的核心原因。要实现阴影,得用SVG原生的<filter>滤镜来做,下面是具体的修改方案和技巧:
修改后的代码实现
const renderRectSvgNode = ({ nodeDatum, toggleNode }) => ( <g> {/* 定义阴影滤镜 */} <defs> <filter id="dropShadow" x="-20%" y="-20%" width="140%" height="140%"> <feDropShadow dx="0" dy="10" stdDeviation="10" floodColor="rgba(0, 0, 0, 0.1)" /> </filter> </defs> <rect width="118" height="40" x="-56" onClick={toggleNode} style={{ fill: "white", stroke: "none", }} filter="url(#dropShadow)" {/* 给矩形应用阴影滤镜 */} /> <text fill="black" strokeWidth="1" x="0" y="25" dominantBaseline="middle" textAnchor="middle" > {nodeDatum.name} </text> </g> );
实用技巧
- 复用滤镜提升性能:如果多个节点都需要阴影,别把
<defs>放在自定义节点函数里,把它移到组件外层的SVG容器中,避免每个节点重复渲染滤镜定义。 - 自定义阴影样式:调整
<feDropShadow>的参数就能改变阴影效果:dx:控制阴影水平偏移量dy:控制阴影垂直偏移量stdDeviation:控制阴影模糊程度floodColor:设置阴影的颜色和透明度
- 避免阴影被裁剪:滤镜的
x、y、width、height要留足空间,比如设置为x="-20%" y="-20%" width="140%" height="140%",防止阴影超出可视范围被切掉。
内容的提问来源于stack exchange,提问作者Samathi kisalka Sapumana
相关产品推荐
相关产品推荐

