如何将Styled Components的transient props传递给嵌套组件?
解决Styled-components嵌套时Transient Props传递问题
当你通过styled(StyledButton)创建嵌套组件时,styled-components默认不会自动将带$前缀的transient props传递给底层的StyledButton——因为这类props原本的设计就是避免传递给DOM元素,组件嵌套时也不会默认向下透传。
下面是两种可行的解决办法:
1. 显式传递单个Transient Prop
使用.attrs()方法,把接收到的$variant手动传递给底层的StyledButton:
const SpecialButton = styled(StyledButton).attrs((props) => ({ $variant: props.$variant }))` // 这里写SpecialButton的自定义样式 `
2. 批量传递所有Transient Prop
如果需要传递多个带$前缀的props,可以通过过滤属性的方式批量传递,避免逐个手动写:
const SpecialButton = styled(StyledButton).attrs((props) => { // 筛选出所有以$开头的props const transientProps = Object.fromEntries( Object.entries(props).filter(([key]) => key.startsWith('$')) ); return transientProps; })` // 这里写SpecialButton的自定义样式 `
不管用哪种方法,底层的StyledButton依然会保留transient props的特性——不会把$variant传递给DOM的<button>元素,只是在组件层级之间完成了props的透传。
内容的提问来源于stack exchange,提问作者wwilkowski
相关产品推荐
相关产品推荐

