如何通过将 SVG 作为 prop 传递来使用 React 样式组件设置 SVG 样式?
Posted
技术标签:
【中文标题】如何通过将 SVG 作为 prop 传递来使用 React 样式组件设置 SVG 样式?【英文标题】:How to style an SVG using React styled components by passing the SVG as prop? 【发布时间】:2022-01-01 19:34:10 【问题描述】:我有这个 SVG,从 figma 导入的:
import React from 'react';
function CloseIcon()
return (
<svg
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_5301_20199)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M19.8539 4.85394C20.0491 4.65868 20.0491 4.3421 19.8539 4.14683C19.6586 3.95157 19.342 3.95157 19.1468 4.14683L12.0007 11.2929L4.85372 4.14634C4.65845 3.95108 4.34187 3.95109 4.14661 4.14636C3.95136 4.34162 3.95136 4.65821 4.14663 4.85346L11.2936 12L4.14688 19.1467C3.95162 19.342 3.95162 19.6586 4.14688 19.8538C4.34214 20.0491 4.65873 20.0491 4.85399 19.8538L12.0007 12.7071L19.1467 19.8529C19.342 20.0481 19.6586 20.0481 19.8539 19.8528C20.0491 19.6576 20.0491 19.341 19.8538 19.1457L12.7078 12L19.8539 4.85394Z"
fill="#00A989"
/>
</g>
<defs>
<clipPath id="clip0_5301_20199">
<rect fill="white" />
</clipPath>
</defs>
</svg>
);
export default CloseIcon;
然后将 SVG 导入到我的组件中,在屏幕上正确呈现为来自 Figma 的原始样式。但是当我使用样式化组件对其进行样式化时,不会应用任何样式。有什么问题?
import CloseIcon from '../../../Icons/CloseIcon';
import styled from 'styled-components';
<ClosingIcon
aria-label="Close Modal"
onClick=() => setShowModal((prev) => !prev)
/>
const ClosingIcon = styled(CloseIcon)`
cursor: pointer;
position: absolute;
top: 14px;
right: 32px;
/* width: 32px;
height: 32px; */
padding: 0;
z-index: 10;
`;
【问题讨论】:
【参考方案1】:您需要将 classname 属性传递给子组件,
function CloseIcon( className )
return (
<svg
className=className --> like this
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clipPath="url(#clip0_5301_20199)">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M19.8539 4.85394C20.0491 4.65868 20.0491 4.3421 19.8539 4.14683C19.6586 3.95157 19.342 3.95157 19.1468 4.14683L12.0007 11.2929L4.85372 4.14634C4.65845 3.95108 4.34187 3.95109 4.14661 4.14636C3.95136 4.34162 3.95136 4.65821 4.14663 4.85346L11.2936 12L4.14688 19.1467C3.95162 19.342 3.95162 19.6586 4.14688 19.8538C4.34214 20.0491 4.65873 20.0491 4.85399 19.8538L12.0007 12.7071L19.1467 19.8529C19.342 20.0481 19.6586 20.0481 19.8539 19.8528C20.0491 19.6576 20.0491 19.341 19.8538 19.1457L12.7078 12L19.8539 4.85394Z"
fill="#00A989"
/>
</g>
<defs>
<clipPath id="clip0_5301_20199">
<rect fill="white" />
</clipPath>
</defs>
</svg>
);
参考:https://styled-components.com/docs/advanced#existing-css
【讨论】:
我会在样式组件 "ClosingIcon" 中添加什么?道具? 没什么,检查链接 - styled-components.com/docs/advanced#existing-css以上是关于如何通过将 SVG 作为 prop 传递来使用 React 样式组件设置 SVG 样式?的主要内容,如果未能解决你的问题,请参考以下文章
通过 CreateAppContainer 传递 props