Javascript 如何将样式应用于SVG元素数组
我有一个Javascript 如何将样式应用于SVG元素数组,javascript,css,reactjs,svg,styled-components,Javascript,Css,Reactjs,Svg,Styled Components,我有一个.svg图标数组,其中每个图标都有一些我需要覆盖的属性: <svg width="24" height="24" viewBox="0 0 24 24"> ... </svg> //有效,但是, //图标太多了 const SocialBar=()=>( ... ); 这样设置svg组件的样式是行不通的: // Won't override the width="24" height="24" properties const StyledIcon = sty
.svg
图标数组,其中每个图标都有一些我需要覆盖的属性:
<svg width="24" height="24" viewBox="0 0 24 24"> ... </svg>
//有效,但是,
//图标太多了
const SocialBar=()=>(
...
);
这样设置svg
组件的样式是行不通的:
// Won't override the width="24" height="24" properties
const StyledIcon = styled(Github)`
width: 50;
height: 50;
`;
这是一种方法
//Github.js
import React from "react";
export default function Github({height, width}) {
return (
<svg width={width} height={height} viewBox="0 0 24 24"> ... </svg>
);
}
//Github.js
从“React”导入React;
导出默认函数Github({height,width}){
返回(
...
);
}
然后你想在哪里使用它
<Github height={24} width={24} />
相对于您已有的代码示例,我不能完全确定您的请求是什么。您是否试图避免使用
React.cloneElement
?将图标数组作为函数,而不是jsx元素<代码>将其映射到jsx版本,并将样式应用到每个版本
const icons = [
Github,
Facebook,
Twitter,
]
buildIcons() {
const style = {
//..
}
return icons.map((icon, idx) => (
<icon style={style} key={idx}/>
))
}
const图标=[
github,
脸谱网,
啁啾
]
buildIcons(){
常量样式={
//..
}
返回icons.map((icon,idx)=>(
))
}
使用索引作为键是可行的,但是如果您可以找到每个图标特有的不同属性,那就更好了。您可以使用元素(如
i
)包装SVG,并使用样式化组件中定义的一些CSS对其中的任何SVG
子项进行样式化(您也可以将目标设置为g
和path
)。不幸的是,SVG的使用非常棘手,因此您可能需要手动将SVG xml复制/粘贴到JS文件中(如果您使用,您可以导入)
工作示例(将SVG复制/粘贴到JS文件中——第一个示例为默认值,第二个示例在道具中传递,第三个示例在多个道具中传递):
Icon/Icon.js(此组件接受生成的
className
样式化组件以及放置在其中的任何子组件)
它有什么帮助?我如何将其应用于图标数组?这就像应用一个内联样式,这样我需要为每个图标创建一个函数。我试图在js中使用css为每个图标设置样式,顺便说一句,您的代码将无法工作,因为图标
需要大写,否则react将无法识别它。所以像这样?jss似乎有多个HOC你可用
const icons = [
Github,
Facebook,
Twitter,
]
buildIcons() {
const style = {
//..
}
return icons.map((icon, idx) => (
<icon style={style} key={idx}/>
))
}
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;
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;