【问题标题】:How can I place text inside an SVG circle with React JS?如何使用 React JS 在 SVG 圆圈内放置文本?
【发布时间】:2015-11-23 15:22:12
【问题描述】:

我有以下代码:

import React from 'react';

var SVGComponent = React.createClass({
    render: function() {
        return <svg {...this.props}>{this.props.children}</svg>;
    }
});

var Circle = React.createClass({
    render: function() {
        return <circle {...this.props}>{this.props.children}</circle>;
    }
});

var MakeCircles = React.createClass({

    render: function () {
        return(
            <div>
                <SVGComponent height="110" width="500">
                    <Circle 
                        cx="50" cy="55" r="45"
                        fill="none"
                        stroke="#F0CE01" strokeWidth="4" />     
                </SVGComponent>
            </div>
        );
    }
});
export default MakeCircles

我正在尝试在圆圈内添加一些文字,但发现它非常困难。有什么/一些插件可以帮助我解决这个问题吗?

【问题讨论】:

  • “试图在圆圈内获取一些文本”到底是什么意思?您的示例中的此文本在哪里?
  • 对不起,我把它从代码中去掉了,因为它不起作用。我已经尝试将它放在 SVGComponent 标签之外,但似乎我需要依靠定位才能将它放到正确的位置。我希望有一个更优雅的解决方案,可能涉及我创建的 SVGComponent 或 Circle 类。
  • 您是希望圆圈设置为固定大小,还是调整为文本大小?
  • 我建议去掉 SVGComponent 和 Circle 组件。使用 代替,您将获得相同的结果。除非您已经知道这些组件将解决哪些额外的属性或行为,否则我认为它们会使您的代码库(或示例)更大更复杂,并且永远不会达到目的。

标签: javascript css svg reactjs


【解决方案1】:

圆圈是一个层,文本节点也是如此。您必须将它们作为单独的层,并使它们看起来好像属于一起:

<SVGComponent height="110" width="500">
    <Circle cx="50" cy="55" r="45" fill="none" stroke="#F0CE01" strokeWidth="4" />
    <text textAnchor="middle" x="250" y="55">Circle Text</text>
</SVGComponent>

【讨论】:

  • 小东西:text-anchor 在 React 中应该是 textAnchor
  • 这对我不起作用.. 只有文本呈现 &lt;div height="110" width="500"&gt; &lt;circle cx="50" cy="55" r="45" fill="none" stroke="#F0CE01" strokeWidth="4" /&gt; &lt;text textAnchor="middle" x="250" y="55"&gt; Circle Text&lt;/text&gt; &lt;/div&gt;
猜你喜欢
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2020-10-19
  • 2016-05-31
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
相关资源
最近更新 更多