You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何向MUI Styled元素传递自定义Props会触发DOM元素警告?

问题

我用React+TypeScript配合MUI v5开发,给div设置样式时控制台报了这个错:

Warning: React does not recognize the openFilterDrawer prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase openfilterdrawer instead. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:55:09