SVG viewbox error with React

时间秒杀一切 提交于 2021-01-28 07:23:57

问题


I cannot for the life of me figure out what's going wrong here. I have the following component:

import React, { Component } from 'react';

class MySvg extends Component {
  render() {
    return (
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {this.props.width} {this.props.height}"></svg>
    );
  }
}

export default MySvg;

When I try to render the component, I get the following error:

Error: <svg> attribute viewBox: Expected number, "0 0 {this.props.widt…"...

I am 100% sure that both props are numbers. They have a typeof number when I console.log, and they are passed as numbers. Is this a problem with React?


回答1:


The problem is your props are inside the string and it doesn't evaluate and get assigned because of that. Use something like this instead.

<svg xmlns="http://www.w3.org/2000/svg" viewBox={"0 0 "+ this.props.width + " " + this.props.height}></svg>

In this way, we basically create the value by concatenating props and strings inside the brackets. Because inside the brackets it is all JavaScript.




回答2:


You can also use string interpolation to solve this in a more readable way:

<svg xmlns="http://www.w3.org/2000/svg" viewBox=`0 0 ${this.props.width} ${this.props.height}`></svg>


来源:https://stackoverflow.com/questions/44029112/svg-viewbox-error-with-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!