[英]Prop TypeScript Error With React Component, Using Styled-Components
I'm creating a Link component that has an option to change color to gray, using the disabled
prop.我正在创建一个 Link 组件,该组件可以使用
disabled
道具将颜色更改为灰色。 When I hover over {({ disabled }
, TypeScript is giving me a Property 'disabled' does not exist on type 'Pick<DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>
error.当我 hover over
{({ disabled }
, TypeScript 给我一个Property 'disabled' does not exist on type 'Pick<DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>
错误。
Syntax looks correct, not sure what I'm missing here.语法看起来正确,不确定我在这里缺少什么。
const StyledLink = styled.a`
color: blue;
${({ disabled }) =>
disabled &&
css`
color: gray;
`}
`;
export type TextLinkProps = {
/**
* text to be passed in as a link
*/
link: string;
/**
* text to be rendered in the component.
*/
children: React.ReactNode;
/**
* If `true`, color will be gray.
*/
disabled?: boolean;
};
export function TextLink({ children, link, disabled = false }: TextLinkProps) {
return (
<StyledLink href={link} disabled={disabled}>
{children}
</StyledLink>
);
}
You should specify the props types you get in your styled component, as such:您应该指定您在样式化组件中获得的道具类型,如下所示:
const StyledLink = styled.a<{ disabled?: boolean }>``
Also just noticed, you can simplify you styles to omit css
:还刚刚注意到,您可以简化 styles 以省略
css
:
${({ disabled }) => disabled && "color: gray"};
TypeScript is right: anchor elements don't have attribute disabled
. TypeScript 是对的:锚元素没有属性
disabled
。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.