如何在React中使用markerEnd绘制箭头

3

我想用React绘制箭头。我发现支持maker-end,参见:React文档。它被称为markerEnd而不是marker-end。它期望一个'url(#markerArrow)',但在React中似乎无法工作。如何使用SVG和React制作箭头? 这是我的一种方法,在组件的子类渲染函数中:它绘制了线条,但没有箭头。

render() {
    return(
        <div>
            <svg className='Line' style={{ height:height, width:width, top:top, left:left }}>
                <defs>
                    <marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6"
                            orient="auto">
                        <path d="M2,2 L2,11 L10,6 L2,2" style={{fill: '#000000'}} />
                    </marker>
                </defs>
                <line x1={lx1} y1={ly1} x2={lx2} y2={ly2} markerEnd={ 'url(#markerArrow)' }  style={{ stroke: 'red', strokeWidth: 2 }} />
            </svg>
        </div>
    );
}

缺失箭头图像 红线左下角应该有一个箭头。


markerEnd是一个属性,而不是一个样式属性。 - Wouter J
好的,我已将其更改为<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} markerEnd={ 'url(#markerArrow)' } style={{ stroke: 'red', strokeWidth: 1 }} />,但仍然没有箭头 :( - zeiteisen
渲染该行吗? - Pavan Teja
2个回答

2

请将<defs>标签放在svg元素内

<defs>
  <marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6" orient="auto">
    <path d="M2,2 L2,11 L10,6 L2,2" />
  </marker>
</defs>
<svg width=200 height=200>
  <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600; marker-end: url(#markerArrow)" />

</svg>



<svg width=200 height=200>
  <defs>
    <marker id="markerArrow1" markerWidth="13" markerHeight="13" refX="2" refY="6" orient="auto">
      <path d="M2,2 L2,11 L10,6 L2,2" />
    </marker>
  </defs>
  <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600; marker-end: url(#markerArrow1)" />

</svg>

如果这个方法不起作用,尝试将<defs>移动到React组件外,并放置在页面中单独的svg中。您可以在此处检查实现。


谢谢你的回答。但是在React中没有maker-end,只有makerEnd。我按照你说的移动了<defs>,但是很遗憾仍然没有箭头。 - zeiteisen

0

为了帮助其他寻找 React 中 marker-end 实现的人:

你的代码是完全正确的!

很可能存在另一个问题。也许有不同的元素在你的<line> 上方。你可以通过给所有元素添加 opacity 属性来检查。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接