如何为作为props传入的styled-icons图标动态添加样式避免告警
告警原因
函数组件内部定义styled组件会导致每次组件渲染时都生成全新的组件实例,触发不必要的DOM重建、样式重复注入,甚至可能导致子组件状态丢失,因此styled-components会抛出对应告警。
最优实现方案
将带通用样式的图标组件提到组件外部全局定义,通过styled-components内置的as属性动态绑定传入的icon组件,上层调用逻辑完全不需要修改:
import styled from 'styled-components' // 全局只初始化一次带通用样式的图标容器 const StyledIcon = styled.div` color: #807da0; width: 1.75rem; margin: 0 1.25rem 0 0.75rem; ` const InputRounded = ({ type, placeholder, icon }) => { return ( <Container> <Input type={type} placeholder={placeholder} /> {icon && <StyledIcon as={icon} />} </Container> ) }
as属性是styled-components专门提供的动态切换底层渲染组件的能力,完全符合官方最佳实践,不会产生告警也没有额外性能损耗。
备选实现方案
如果你不想使用as属性,也可以通过样式包裹的方式实现,效果完全一致:
import styled from 'styled-components' const IconWrapper = styled.span` color: #807da0; width: 1.75rem; margin: 0 1.25rem 0 0.75rem; ` const InputRounded = ({ type, placeholder, icon: Icon }) => { return ( <Container> <Input type={type} placeholder={placeholder} /> {Icon && ( <IconWrapper> <Icon /> </IconWrapper> )} </Container> ) }
内容的提问来源于stack exchange,提问作者relaxxpls
相关产品推荐
相关产品推荐

