typescript 为什么将自定义属性传递给MUI样式的元素会导致出现DOM元素警告?

uxhixvfz  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(125)

我正在React with Typescript中使用mui v5。我试图设置div样式,但在控制台中遇到以下错误:
警告:React无法识别DOM元素上得openFilterDrawer属性.如果您有意让它作为自定义属性出现在DOM中,请将其拼写为小写得openfilterdrawer.如果您意外地从父组件传递了它,请将其从DOM元素中删除.
我做错了什么?
下面是我的代码:

type ChipsContainerProps = {
    openFilterDrawer: boolean
  }

 const ChipStyled = {
    Container: styled('div')<ChipsContainerProps>(
      ({ theme, openFilterDrawer }) => ({
          //leaving out irrelevant theme code
          ...(openFilterDrawer && {
            transition: theme.transitions.create('margin', {
              easing: theme.transitions.easing.easeOut,
              duration: theme.transitions.duration.enteringScreen,
            }),
            marginLeft: 0,
            paddingLeft: '0rem',
          }),
        },        
      }),
    ),
  }
dwbf0jvd

dwbf0jvd1#

问题是MUI正在将您传递给底层divopenFilterDrawer属性转发,并且由于openFilterDrawer不是div的有效属性,因此React会引发该警告。
若要清除警告,您应该传递包含shouldForwardProps函式的对象,以从产生的div中筛选prop。例如:

const ChipStyled = {
  Container: styled("div", {
    shouldForwardProp: (prop) => prop !== "openFilterDrawer" // <-- Here
  })<ChipsContainerProps>(({ theme, openFilterDrawer }) => ({
    //leaving out irrelevant theme code
    ...(openFilterDrawer && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen
      }),
      marginLeft: 0,
      paddingLeft: "0rem"
    })
  }))
};

相关问题