![](/img/trans.png)
[英]React component unit test with enzyme fails when rendering Image tag with svg
[英]React svg image not rendering with use tag
我這里有一個簡單的組件,它接收任何 svg 圖像和描邊顏色,並相應地呈現樣式化的 svg。 沒有錯誤消息,只是沒有呈現。 我嘗試用一個簡單的圖像替換 SVG 和 use 標簽,它可以很好地渲染組件——這意味着 SVG 和 use 標簽是這里的問題。 不知道為什么。 有什么建議么?
import React from 'react
import styled from 'styled-components'
import Truck from './Truck.svg'
const SVG = styled.svg`
stroke: ${props => props.stroke || '#66CC00'};
`;
const Icon = props => {
const { src } = props;
return (
<SVG xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" {...props}>
<use xlinkHref={src} />
</SVG>
);
};
const RenderIcon = () => <Icon src={Truck} stroke={red} />
作為參考,這是我試圖復制的內容: https://stackblitz.com/edit/react-6cr17y
使用image
SVG 元素,我可以看到 svg 圖像。
更新代碼- 更新代碼以使用use
和href
。 還更新了沙箱。 這應該正確應用stroke
屬性。
import React from "react";
import styled from "styled-components";
import { ReactComponent as Truck } from "./Settings.svg";
const SVG = styled.svg`
stroke: ${(props) => props.stroke || "#66CC00"};
`;
const Icon = ({ stroke }) => {
return (
<SVG viewBox="0 0 512 512" stroke={stroke}>
<Truck />
<use href={Truck} />
</SVG>
);
};
const RenderIcon = () => <Icon stroke={"red"} />;
export default RenderIcon;
這里的工作示例 - https://codesandbox.io/s/vibrant-clarke-73g8g?file=/src/App.js
要么,
import React from "react";
import styled from "styled-components";
import { ReactComponent as Truck } from "./Settings.svg";
const SVG = styled.svg`
stroke: ${(props) => props.stroke || "#66CC00"};
`;
const Icon = ({ src, stroke }) => {
return (
<SVG viewBox="0 0 512 512" stroke={stroke}>
{src()}
<use href={src} />
</SVG>
);
};
const RenderIcon = () => <Icon src={Truck} stroke={"red"} />;
export default RenderIcon;
如果您使用的是 Create React App,您可以這樣做:
import React from "react";
import { ReactComponent as Truck } from "./truck.svg";
export default function App() {
return (
<div className="App">
<MySvgComponent stroke="blue" svgToRender={() => <Truck />} />
</div>
);
}
function MySvgComponent({ strokeColor = "red", svgToRender }) {
return (
<>
{svgToRender()}
<svg>
<use href="#mytruck" fill="green" stroke={strokeColor} />
</svg>
</>
);
}
如果沒有,您需要安裝SVGR並將其用作 webpack 加載程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.