【问题标题】:SVG viewbox error with ReactReact 的 SVG 视图框错误
【发布时间】:2020-01-03 12:38:17
【问题描述】:

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

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;

当我尝试渲染组件时,我收到以下错误:

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

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

【问题讨论】:

    标签: reactjs svg


    【解决方案1】:

    问题是您的道具在字符串内,因此不会评估和分配。改用这样的东西。

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

    通过这种方式,我们基本上通过在括号内连接道具和字符串来创建值。因为括号内都是 JavaScript。

    【讨论】:

      【解决方案2】:

      您还可以使用字符串插值以更易读的方式解决此问题:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        相关资源
        最近更新 更多