首页 > 解决方案 > 无法在 React 中缩放 SVG

问题描述

我在 React 功能组件中有一个 SVG:

import React from 'react';

function mySVG({ colour, width, height, scale }) {
    const scaleFactor = 'scale:(' + { scale } + ')';

    return (
        <svg width={width} height={height}>
            >
            <g transform={scaleFactor}>
               <path d="M150 0 L75 200 L225 200 Z" 
                    fill={colour}
                    stroke={colour}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
            </g>
        </svg>
    );
}

export default mySVG;

这怎么不是根据 scale 道具缩放的?

标签: reactjssvg

解决方案


问题出在您的语法中,应该没有:in'scale(' + { scale } + ')';

import React from 'react';

function mySVG({ colour, width, height, scale }) {
    const scaleFactor = 'scale(' + { scale } + ')';

    return (
        <svg width={width} height={height}>
            <g transform={scaleFactor}>
               <path d="M150 0 L75 200 L225 200 Z" 
                    fill={colour}
                    stroke={colour}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
            </g>
        </svg>
    );
}

export default mySVG;

我为它添加了代码沙盒: https ://codesandbox.io/s/winter-architecture-uw45f


推荐阅读