我定义了这样的“Logo”组件:
const Logo = ({ className }: { className: string }) => (
<Link to="/" className={className}>
<img src={logo} alt="logo" />
</Link>
);
可以通过传递 className 来设置样式。
但是当我将它与这样的 typescript 一起使用时:
const StyledLogo = styled(Logo)`
margin-left: 4.5rem;
`;
...渲染中的某处:
<StyledLogo />
然后我遇到了这样的错误:
Error:(33, 6) TS2741: Property 'className' is missing in type '{}' but required in type 'Pick & Partial>, "className">'.
如何让 typescript 知道我的所有样式组件都会传递这个 className 属性并且它将始终存在?
最佳答案
通过标记 Logo
as optional 的 className
参数应该可以解决此问题。通过执行以下操作:
/* Add ? after className */
const Logo = ({ className }: { className?: string }) => (
<Link to="/" className={className}>
<img src={logo} alt="logo" />
</Link>
);
const StyledLogo = styled(Logo)`
margin-left: 4.5rem;
`;
/* No ts error reported now */
<StyledLogo />
希望有帮助!
<小时/>更新
或者,为了避免上面可选的 className
方法,您可以采用以下方法:
/* Define type to minimise verbosity */
type LogoProps = { className: string };
/* Define strongly typed Logo function with defined type */
const Logo = (props: LogoProps) => (
<Link to="/" className={props.className}>
<img src={"logo"} alt="logo" />
</Link>
);
/* TS explicitly aware of prop set being passed to Logo via type */
export const StyledLogo = styled((props: LogoProps) => <Logo {...props} />)`
margin-left: 4.5rem;
`;
/* Usage */
<StyledLogo />
此方法确保 TS 知道传递给 Logo
组件的实际 prop 集。
关于javascript - 样式组件缺少 className,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57350584/