javascript - 在 React 中创建带箭头的线

标签 javascript svg reactjs

使用 , 元素创建带箭头的线,如下例所示(不是我的代码): http://jsfiddle.net/m1erickson/9aCsJ/

我尝试将其转换为 React 组件,如下所示: http://jsfiddle.net/kdgqmt55/3/

但我看到的只是一条红线,没有箭头。

这是因为 React 运行时无法识别标记或 defs 元素吗?

(满足 Stackoverflow 的 JSFiddle 条件的代码:

React.render(<Arrow start={{x:0, y:0}} stop={{x:400, y:400}} />,
                                       $("#my-arrow").get(0)
                                       );  

)

最佳答案

这是使用 React 渲染 SVG 元素的一个不幸的方面。它们将一堆属性列入白名单,并且不在列表中的属性将被删除,因此您将丢失一堆标记宽度、标记高度和许多其他属性。

https://facebook.github.io/react/docs/tags-and-attributes.html

这里有关于修复此问题的讨论 https://github.com/facebook/react/issues/140

目前,对于未定义的属性,您可以将它们放入 componentDidMount 中。 (添加了几个来演示,但没有完全修复示例)

var Arrow = React.createClass({
       componentDidMount: function(){
           var markerNode = React.findDOMNode(this.refs.marker)
           var markerEndNode = React.findDOMNode(this.refs.markerEndNode)

           markerNode.setAttribute('markerWidth', 13)
           markerNode.setAttribute('markerHeight', 13)
           markerNode.setAttribute('refx', 2)
           markerNode.setAttribute('refy', 6)
       },
       render: function() {
            var style = {
                position: "absolute",
                zIndex: 200,
            };

            path_d = "M" + this.props.start.x + "," + this.props.start.y + " "
            path_d += "L" + this.props.stop.x + "," + this.props.stop.y

            return (
                <svg width="300" height="100" style={style} >
                    <defs>
                        <marker ref="marker" id="arrow">
                        <path d="M2,1 L2,10 L10,6 L2,2" style={{fill:"red"}} />
                        </marker>
                    </defs>

                <path ref="markerEndNode" d="M30,150 L100,50"
                    style={{stroke:"red", strokeWidth: "1.25px", fill: "none"}}
                />
            </svg>);
        },
    });

关于javascript - 在 React 中创建带箭头的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666274/

相关文章:

javascript - 在 JS 中从数组中选择项目的副本

SVG 翻译时以 em 为单位?

javascript - 从 parent 到 child 的传递功能

javascript - Docker,脚本似乎可以正确构建并运行,但无法在本地主机上连接

javascript - 页面加载后交换(替换)图像源?

javascript - 按 id 迭代 anchor

html - 如何让 SVG 中的 Wings 移动?

javascript - 替换旧内容 d3

reactjs - useEffect 内的 onClick 和 addEventListener 之间的 click 事件顺序差异

javascript - 复选框第一次不反射(reflect)其选中值