我有一组 .svg
图标,其中每个图标都有一些我需要覆盖的属性:
<svg width="24" height="24" viewBox="0 0 24 24"> ... </svg>
import styled from 'styled-components';
import Github from 'assets/github.svg';
import Facebook from 'assets/facebook.svg';
import Twitter from 'assets/twitter.svg';
...
const icons = [
<Github />,
<Facebook />,
<Twitter />,
...
];
我想为每个图标应用相同的样式无需重复代码并使用CSS-in-JS
。
到目前为止,我的解决方案存在一些问题:
// Works but,
// I want to use CSS-in-JS like styled-components
// for easier maintenance
const iconStyle = {
width: 50,
height: 50
};
const SocialBar = () => (
<IconBar as={FlexBox}>
{icons.map((icon, key) => (
<div key={key}>{React.cloneElement(icon, iconStyle)}</div>
))}
</IconBar>
);
// Works but,
// there are too many icons
const SocialBar = () => (
<IconBar as={FlexBox}>
<Github style={iconStyle} />
<Facebook style={iconStyle} />
...
</IconBar>
);
像这样设置 svg
组件的样式是行不通的:
// Won't override the width="24" height="24" properties
const StyledIcon = styled(Github)`
width: 50;
height: 50;
`;
最佳答案
您可以用一个元素(如 i
)包装 SVG,并使用在样式化组件中定义的一些 CSS(您可以还针对 g
和 path
)。不幸的是,SVG 使用起来非常棘手,因此您可能需要手动将 SVG xml 复制/粘贴到 JS 文件中(如果您使用的是 CRA ,则可以导入 ReactComponent from an SVG )。
工作示例(将 SVG 复制/粘贴到 JS 文件中——第一个示例是默认的,第二个示例传入 props,第三个示例传入多个 props):
Icon/Icon.js(此组件接受样式化的组件生成的 className
和放置在其中的任何 children
)
import React from "react";
import PropTypes from "prop-types";
const Icon = ({ className, children }) => (
<i className={className}>{children}</i>
);
Icon.propTypes = {
className: PropTypes.string.isRequired,
children: PropTypes.node.isRequired
};
export default Icon;
Icon/index.js(这将为上面的 Icon
组件设置样式;随后它将为 children
设置样式)
import styled from "styled-components";
import Icon from "./Icon";
const StyledIcon = styled(Icon)`
margin: 0 20px;
svg {
fill: ${({ fill }) => fill || "#03a9f3"};
height: ${({ dimension }) => dimension || "50px"};
width: ${({ dimension }) => dimension || "50px"};
}
`;
export default StyledIcon;
关于javascript - 如何将样式应用于 SVG 元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57103903/