reactjs - React 无法识别 DOM 元素上的 X 属性
问题描述
我是初学者开发人员,我正在研究 react(gatsby、TS、样式化组件)项目。我收到此错误:
“React 无法识别isOpen
DOM 元素上的 prop。如果您故意希望它作为自定义属性出现在 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;
};
我确信我错过了一些基本的反应东西或其他东西。也许有人可以帮助我并解释这个错误的原因。
解决方案
发生这种情况时,是因为传递给样式化组件的所有道具随后也会传递给您正在设置样式的 DOM 元素。
您可能有一个如下所示的组件:
const SvgStyled = styled(SVG)<{ isOpen: boolean }>`
// your CSS and logic referencing the `isOpen` prop
`;
要解决此问题,您需要重构样式化的组件定义,并仅将所需的道具显式传递给正在设置样式的元素。使用匿名函数组件并解构您不想传递给 DOM 元素的道具,并传播其余的道具。这确保了为其创建 CSS 类的className
道具styled-components
被传递。
例子:
interface SvgStyledProps {
className?: string,
isOpen: boolean,
}
const SvgStyled = styled(({ isOpen, ...props}) => (
<Svg {...props} />
))<SvgStyledProps>`
// your CSS and logic referencing the `isOpen` prop
`;
有关任何其他 Typescript 细节/注意事项,styled-components
请参阅docs。