【问题标题】:create a responsive svg with react使用 react 创建响应式 svg
【发布时间】:2018-04-13 10:36:39
【问题描述】:

我想创建一个 svg,它可以很容易地按我给它的任何宽度进行缩放。在那个 svg 中,我有一个圆和带有相对路径的路径,所以我希望它可以轻松扩展。

但是由于某种原因 x,y 的位置不对。

可以看到下图,圆圈有(x,y)=(0,0) 但它设置在中间。 我认为“viewBox”会导致问题。

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 具有响应性? ExclamationIcon创建的外部svg或svg?
  • 第二个 svg 应该是响应式的。我将它用作 html 中的简单图标,但我不得不在 svg 中使用它并收到此错误:/

标签: javascript reactjs d3.js svg


【解决方案1】:

如果在内部 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')
);

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 2016-04-01
    • 2014-11-14
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2017-11-18
    相关资源
    最近更新 更多