使用React创建响应式的SVG

3

我想创建一个svg,这个svg可以根据任何给定的宽度轻松缩放。在这个svg中,我有一个带有相对路径的圆和路径,所以我希望它易于缩放。

但是由于某些原因,x,y的位置不正确。

您可以在下面看到图像,圆形具有(x,y)=(0,0),但设置在中间。我认为“viewBox”会引起问题。

enter image description here

jsfiddle链接: https://jsfiddle.net/tzookb/69z2wepo/174297/

代码:

const ExclamationIcon = props => (
    <svg {...props} viewBox="0 0 140 140">
      <circle fill="#f66868" cx="70" cy="70" r="70" />
      <g transform="translate(58,30)">
        <path fill="white" d="M 11,56.7 L 9,56.7 L 4.2,13.2 C 4,11.4 4,10 4,9 C 4,7 4.5,4.9 5.6,3.5 C 7,2.2 8.3,1.5 10,1.5 C 11.7,1.5 13,2.2 14.4,3.5 C 15.5,4.9 16,7 16,9 C 16,10 16,11.4 15.8,13.2 z M 10,64 A 6,6 0 1,1 10,76 A 6,6 0 1,1 10,64 z"/>
      </g>
    </svg>
);


class Hello extends React.Component {
  render() {
    return (
        <div>
        asdas
        <svg className="main">
          <rect x="20" y="20" width="100" height="40" fill="red" />

          <ExclamationIcon width="30" x="0" y="0" />
        </svg>


      </div>
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

这是非常好奇的行为。我们使用外部SVG有什么特别的原因吗?你想要使哪个SVG具有响应性?是外部SVG还是由“ExclamationIcon”创建的SVG? - Chirag Ravindra
第二个svg应该是响应式的。我在html中将其用作简单图标,但我必须在svg中使用它,结果出现了这个错误 :/ - Tzook Bar Noy
1个回答

2

看起来如果在内部svg上设置高度,这个问题就会消失。我猜测如果没有设置高度,它会自动占用所有可用的高度并居中。我希望我有更好的解释,但这完全让我困惑了。

JS Fiddle

const ExclamationIcon = props => (
    <svg {...props} viewBox="0 0 140 140">
      <circle fill="#f66868" cx="70" cy="70" r="70" />
      <g transform="translate(58,30)">
        <path fill="white" d="M 11,56.7 L 9,56.7 L 4.2,13.2 C 4,11.4 4,10 4,9 C 4,7 4.5,4.9 5.6,3.5 C 7,2.2 8.3,1.5 10,1.5 C 11.7,1.5 13,2.2 14.4,3.5 C 15.5,4.9 16,7 16,9 C 16,10 16,11.4 15.8,13.2 z M 10,64 A 6,6 0 1,1 10,76 A 6,6 0 1,1 10,64 z"/>
      </g>
    </svg>
);


class Hello extends React.Component {
  render() {
    return (
     <div>
        asdas
        <svg className="main">
          <rect x="20" y="20" width="100" height="40" fill="red" />

          <ExclamationIcon width="30" height="30" x="0" y="0" />
        </svg>

      
      </div>
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);


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