为何向MUI Styled元素传递自定义Props会触发DOM元素警告?
问题
我用React+TypeScript配合MUI v5开发,给div设置样式时控制台报了这个错:
Warning: React does not recognize the
openFilterDrawerprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercaseopenfilterdrawerinstead. If you accidentally passed it from a parent component, remove it from the DOM element.
我的代码是这样的:
type ChipsContainerProps = { openFilterDrawer: boolean } const ChipStyled = { Container: styled('div')<ChipsContainerProps>( ({ theme, openFilterDrawer }) => ({ // 省略无关主题代码 ...(openFilterDrawer && { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, paddingLeft: '0rem', }), }, }), ), }
解决方法
问题根源是MUI的styled组件默认会把所有传入的props都传给底层DOM元素,但openFilterDrawer只是用来控制样式的逻辑参数,根本不需要传到DOM上。
你只要用MUI提供的shouldForwardProp配置,过滤掉这个不需要传递的props就行,修改后的代码如下:
type ChipsContainerProps = { openFilterDrawer: boolean } const ChipStyled = { Container: styled('div', { // 告诉styled组件不要把openFilterDrawer传给DOM元素 shouldForwardProp: (prop) => prop !== 'openFilterDrawer' })<ChipsContainerProps>( ({ theme, openFilterDrawer }) => ({ // 省略无关主题代码 ...(openFilterDrawer && { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, paddingLeft: '0rem', }), }), ), }
这样修改后,控制台的警告就会消失,因为openFilterDrawer不会再被传递给底层的div元素了。
内容的提问来源于stack exchange,提问作者Natalka
相关产品推荐
相关产品推荐

