reactjs - styled-components:组件...已动态创建
问题描述
我正在尝试创建一个自定义 SVG 图标组件。众所周知,SVG 在 react 中的处理方式与普通 HTML 元素略有不同。
因此,我不能像往常一样在渲染函数之外定义它。这就是我现在所拥有的:
SvgIcon.js
const SvgIcon = ({ stroke, fill, size, icon: Icon, className }) => {
const StyledIcon = styled(Icon).attrs({
viewBox: `0 0 24 24`,
})`
path {
${({ custom_stroke, theme }) =>
custom_stroke &&
`stroke: ${calculateColor({ color: custom_stroke, theme })};`}
${({ custom_fill, theme }) =>
custom_fill &&
`fill: ${calculateColor({ color: custom_fill, theme })};`}
}
height: ${({ size }) => calculateSize({ size })};
width: ${({ size }) => calculateSize({ size })};
`;
return (
<StyledIcon
className={className}
size={size}
custom_fill={fill}
custom_stroke={stroke}
/>
);
};
SvgIcon.propTypes = {
stroke: PropTypes.oneOf(Object.values(SVG_ICON_COLORS)),
fill: PropTypes.oneOf(Object.values(SVG_ICON_COLORS)),
size: PropTypes.oneOf(Object.values(SVG_ICON_SIZES)),
icon: PropTypes.elementType.isRequired,
};
export default SvgIcon;
这是这样使用的:
import { ReactComponent as ArrowUpIcon } from '../ui/icons/arrow-up.svg';
<SvgIcon icon={ArrowUpIcon} size={"small"} stroke={"blue"} fill={"green"} />
但是,在控制台中,styled-components 抱怨:
The component SvgIcon__StyledIcon with the id of "SvgIcon__StyledIcon-sc-77lkhb-0" has been created dynamically.
You may see this warning because you've called styled inside another component.
To resolve this only create new StyledComponents outside of any render method and function component.
如何在没有警告的情况下制作自定义 SvgIcon 组件?
解决方案
我最终只是将 SVG 包装在一个 div 中并通过 CSS 访问样式
const IconWrapper = styled.div`
display: inline-block;
svg {
path {
${({ custom_stroke, theme }) =>
custom_stroke &&
`stroke: ${calculateColor({ color: custom_stroke, theme })};`}
${({ custom_fill, theme }) =>
custom_fill &&
`fill: ${calculateColor({ color: custom_fill, theme })};`}
}
height: ${({ size }) => calculateSize({ size })};
width: ${({ size }) => calculateSize({ size })};
}
`;
const SvgIcon = ({ stroke, fill, size, icon: Icon }) => (
<IconWrapper size={size} custom_fill={fill} custom_stroke={stroke}>
<Icon viewBox="0 0 24 24" />
</IconWrapper>
);
SvgIcon.propTypes = {
stroke: PropTypes.oneOf(Object.values(SVG_ICON_COLORS)),
fill: PropTypes.oneOf(Object.values(SVG_ICON_COLORS)),
size: PropTypes.oneOf(Object.values(SVG_ICON_SIZES)),
icon: PropTypes.elementType.isRequired,
};
export default SvgIcon;
推荐阅读
- javascript - SPTPersistentCache - 通过唯一 ID 缓存视频
- graphql - 如何处理 Vue.JS 中的 Apollo Graphql 查询错误?
- multithreading - 为什么 Rust 互斥锁似乎没有将锁给最后想要锁定它的线程?
- mysql - MYSql 社区版是否支持 Nosql
- verilog - Quartus II 上使用 Verilog 的寄存器的奇怪行为
- datetime - 如何不从设备而是从互联网获取时间?
- python - Python - 存储在变量中的字符串显示为元组
- java - 使用recyclerview时如何避免等待服务器数据的时间过长
- excel - 如何根据收到的时间和主题行在新邮件中保存 Excel 附件?
- python - 如何为作为 Kubernetes 容器运行的 Flask HTTP 服务器实现 HTTPS 支持