React 的 SVG 视窗错误 [英] SVG viewbox error with React

查看:40
本文介绍了React 的 SVG 视窗错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终其一生都无法弄清楚这里出了什么问题.我有以下组件:

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…"...

我 100% 确定这两个道具都是数字.当我 console.log 时,它们有一个 typeof 数字,它们作为数字传递.这是 React 的问题吗?

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?

推荐答案

问题是你的 props 在字符串中,因此它不会评估和分配.改用类似这样的东西.

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>

通过这种方式,我们基本上通过在括号内连接 props 和字符串来创建值.因为括号里面全是 JavaScript.

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

这篇关于React 的 SVG 视窗错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆