React 无法识别 DOM 元素上的 X 属性

React does not recognize the X prop on a DOM element

我是初级开发人员,正在从事 React(gatsby、TS、样式化组件)项目。我收到此错误:

"React 无法识别 DOM 元素上的 isOpen 道具。如果您有意希望它作为自定义属性出现在 DOM 中,请将其拼写为小写 isopen 而不是。如果您不小心从父组件传递了它,请将其从 DOM 元素中删除。"

export const Navigation = () => {
      const [isNavigationOpen, setIsNavigationOpen] = useState(false);
      const { isTablet } = useQuery();
    
      const showNavbar = () => {
        setIsNavigationOpen((previousState) => !previousState);
      };
    
      const renderElement = isTablet ? (
        <>
          <SvgStyled
            src='bars_icon'
            isOpen={isNavigationOpen}
            onClick={showNavbar}
          />
          <MobileNavigation isOpen={isNavigationOpen}>
            {NAVIGATION_DATA.map(({ id, url, text }) => (
              <LinkMobile key={id} to={url}>
                <ExtraSmallParagraph>{text}</ExtraSmallParagraph>
              </LinkMobile>
            ))}
          </MobileNavigation>
        </>
      ) : (
        <FlexWrapper>
          {NAVIGATION_DATA.map(({ id, url, text }) => (
            <LinkDekstop key={id} to={url}>
              <ExtraSmallParagraph>{text}</ExtraSmallParagraph>
            </LinkDekstop>
          ))}
        </FlexWrapper>
      );
    
      return renderElement;
    };

我确定我遗漏了一些基本的 React 内容或其他内容。也许有人可以帮助我并解释这个错误的原因。

发生这种情况是因为传递给样式化组件的所有道具随后也传递给您正在设置样式的 DOM 元素。

您的组件可能如下所示:

const SvgStyled = styled(SVG)<{ isOpen: boolean }>`
  // your CSS and logic referencing the `isOpen` prop
`;

为了解决这个问题,您重构了带样式的组件定义,并明确地只将您想要的道具传递给被设置样式的元素。使用匿名函数组件并解构你不想传递给 DOM 元素的道具,然后传播其余的道具。这确保 styled-components 正在为其创建 CSS class 的 className 道具被传递。

示例:

interface SvgStyledProps {
  className?: string,
  isOpen: boolean,
}

const SvgStyled = styled(({ isOpen, ...props}) => (
  <Svg {...props} />
))<SvgStyledProps>`
  // your CSS and logic referencing the `isOpen` prop
`;

对于任何其他带有 styled-components 的 Typescript specifics/caveats,请参阅 docs