问题
错误信息
Warning: React does not recognize the isExpand prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase isExpand instead. If you accidentally passed it from a parent component, remove it from the DOM element.
问题代码
const CollapseIconButton = styled(IconButton)`
color: #ffffff !important;
svg {
transition: all 250ms ease;
transform: ${({isExpand}) => (isExpand ? 'rotate(180deg)' : '')};
}
`;
解决
根因
isExpand是我们自定义的参数,Emotion会将其透传给下层的DOM,比如<div isExpand=''></div>,但它对div是个无效参数
解决方案
使用shouldForwardProp方法,来过滤掉作为html属性无效的 props
解决示例
模板字符串格式
const CollapseIconButton = styled(IconButton, {shouldForwardProp: (prop) => prop !== 'isExpand'})`
color: #ffffff !important;
svg {
transition: all 250ms ease;
transform: ${({isExpand}) => (isExpand ? 'rotate(180deg)' : '')};
}
`;
CSS对象格式
const CollapseIconButton = styled(IconButton, {
shouldForwardProp: (prop) => prop !== 'isExpand'
})((props) => ({
color: '#ffffff !important',
svg: {
transition: 'all 250ms ease',
transform: props.isExpand ? 'rotate(180deg)' : '',
},
}));
思考:为什么DOM中没有MUI的variant,sx等属性呢?
其实是MUI对自己的组件也做了一层过滤,过滤掉了例如color,variant,sx等props,这也就是为什么MUI不会帮我们给自定义的props加上过滤,而需要我们手动加。
参考: