问题
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