【问题标题】:How to programmatically add SVG shapes to a SVG graphic within a React component?如何以编程方式将 SVG 形状添加到 React 组件中的 SVG 图形?
【发布时间】:2022-01-09 08:23:29
【问题描述】:

如何以编程方式创建在 React 组件中呈现的 SVG 形状?在本例中,我创建了一个包含 20 个点的字符串。但是,将{dots} 放在标签<svg></svg> 之间不起作用。只需将{dots} 放在组件的返回函数中,它就会显示为一个字符串。

我做错了什么?任何帮助和建议都非常感谢!!!

import './SVGLayer.css';
import React from 'react';

const SVGLayer = () => {
  let dots: string = '';

  for (let i = 0; i < 20; i++) {
    dots += `<circle cx="${100 + i * 10}px" cy="100px" r="0.5px" stroke="black" />`;
  }

  return (
    <div className="svg-layer">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        version="1.1"
        width="800px"
        height="600px"
      >
        <circle cx="100px" cy="100px" r="1px" stroke="black" />
        {dots}
      </svg>
    </div>
  );
};

export default SVGLayer;

【问题讨论】:

    标签: reactjs svg


    【解决方案1】:

    您不想使用模板文字,因为模板文字是字符串。 React 看到你的 {dots} 并认为,“好的,bassman21 正在尝试在这里渲染一个字符串。”

    如果 React 看到 JSX(不要担心你的 for 循环,你可以在 JSX 中添加一个 map() 函数),它实际上会创建你想要的组件(它的引擎会用对 React.createComponent() 的调用替换 JSX 元素) ,那么为什么不尝试类似的方法:

    return (
        <div className="svg-layer">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            version="1.1"
            width="800px"
            height="600px"
          >
            <circle cx="100px" cy="100px" r="1px" stroke="black" />
            {/* There are much better ways to do this, but this should illustrate my point nicely */}
            {[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19].map((offset, idx) => <circle key={`circle-${idx}`} cx={`${100 + offset * 10}px`} cy="100px" r="0.5px" stroke="black" />}
          </svg>
        </div>
      );
    

    这将渲染 20 个实际元素,并将您的数据插入到 cx 属性中!

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2018-07-09
      • 2013-08-16
      • 1970-01-01
      • 2017-05-12
      • 2017-04-09
      • 2013-02-18
      • 2016-08-20
      • 2022-09-29
      相关资源
      最近更新 更多