Reactjs 样式化SVG组件
我正在使用React帮助管理我的SVG图标:Reactjs 样式化SVG组件,reactjs,styled-components,Reactjs,Styled Components,我正在使用React帮助管理我的SVG图标: const Trash = ({ fill, width, height, }) => ( <svg width={ `${width}px` } height={ `${height}px` } xmlns="http://www.w3.org/2000/svg" id="Layer_1" data-name="Layer 1" viewBox="0 0 17.92 20.42"> <path style={
const Trash = ({
fill, width, height,
}) => (
<svg width={ `${width}px` } height={ `${height}px` } xmlns="http://www.w3.org/2000/svg" id="Layer_1" data-name="Layer 1" viewBox="0 0 17.92 20.42">
<path style={ { fill } } d="M14,20.3H3.91a0.5,0.5,0,0,1-.5-0.47l-0.89-14A0.5,0.5,0,0,1,3,5.35H14.9a0.5,0.5,0,0,1,.5.53l-0.89,14A0.5,0.5,0,0,1,14,20.3Zm-9.63-1h9.16l0.83-13H3.56Z" />
<rect style={ { fill } } x="5.69" y="5.84" width="1" height="13.98" transform="translate(-0.68 0.35) rotate(-3.1)" />
...
</svg>
);
但当我尝试使用StyledTrashIcon
时,我得到:
函数作为子函数无效。如果返回组件而不是从渲染返回组件,则可能会发生这种情况。或者你是想调用这个函数而不是返回它
改为:
const StyledTrashIcon = styled(TrashIcon()).attrs({
抛出此错误:
无法为组件:[object]创建样式化组件
我现在的风格是这样的,
Arrow
是一个返回SVG的功能组件:
import styled, { ThemeContext } from "styled-components";
import { Arrow } from "src/icons/Arrow";
import React, { useContext } from "react";
export const StyledArrow = () => {
const themeContext = useContext(ThemeContext);
return (
<Arrow
color={themeContext.elements.arrow.color}
width="20px"
height="20px"
/>
);
};
import styled,{ThemeSecontext}来自“styled components”;
从“src/icons/Arrow”导入{Arrow};
从“React”导入React,{useContext};
导出常量StyledArrow=()=>{
const themeContext=useContext(themeContext);
返回(
);
};
可以这样尝试吗:const StyledTrashIcon=styled(TrashIcon)().attrs({
try,它从SVG文件生成JSX,并允许使用react语法控制
的道具如果您的组件使用const
-const StyledTrashIcon=styled,您应该在组件之后定义样式化组件(垃圾)`…`
<TrashIcon fill="#fff" activeFill="#000" />
// styled.js
const StyledTrashIcon = styled(TrashIcon).attrs({
fill: colors.white,
activeFill: colors.sushi,
hoverFill: colors.sushi,
})`
// other styles
`;
const StyledTrashIcon = styled(TrashIcon()).attrs({
import styled, { ThemeContext } from "styled-components";
import { Arrow } from "src/icons/Arrow";
import React, { useContext } from "react";
export const StyledArrow = () => {
const themeContext = useContext(ThemeContext);
return (
<Arrow
color={themeContext.elements.arrow.color}
width="20px"
height="20px"
/>
);
};