javascript - 使用带有 typescript 的样式组件的“as”多态属性
问题描述
我试图实现一个排版反应组件。
正如您在下面看到的,我将变量作为输入道具并将其用作 VariantsMap 对象的索引以获取相应的 html 标记名称。
然后我使用styled-components 'as' 多态道具将其呈现为选定的 html 标记。
但我不断收到此错误:
No overload matches this call. Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & { ...; }, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error. Type 'string' is not assignable to type 'undefined'.
我在@types/styled-component中发现 'as' 道具可以是 'never | undefined',我的 variablesMap 返回字符串类型。
但我真的想将此“as”道具与我的特定于变体的 html 标记选择功能一起使用。
有没有办法解决这个问题?
const variantMap = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
subheading1: 'h6',
subheading2: 'h6',
body1: 'p',
body2: 'p',
};
export const Typography = ({ variant : string }) => {
const selectedComponent = variantMap[variant];
return (<TypographyRoot
as={selectedComponent}
variant={variant}
{...props}
>
{children}
</TypographyRoot>);
}
解决方案
首先,export const Typography = ({ variant : string }) => {}
是无效的语法。
您刚刚将 destructured 的名称更改variant
为string
. 您没有提供类型。
string
即使使用像这里这样的有效类型也会出现错误的原因export const Typography = ({ variant }:{variant: string}) => {}
是variantMap
期望作为键h1
| 'h2' |'h3' ... 键而string
更宽。我愿意打赌您不想将foo
字符串分配给variant
属性。
为了修复它,您只需要使其variantMap
不可变并将适当的约束应用于variantMap
:
import React from 'react'
import styled from "styled-components";
const Div = styled.div`
color: red;
`;
const VariantMap = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
subheading1: 'h6',
subheading2: 'h6',
body1: 'p',
body2: 'p',
} as const;
type Props = {
variant: keyof typeof VariantMap
}
export const Typography = ({ variant }: Props) => {
const selectedComponent = VariantMap[variant];
return <Div
as={selectedComponent}
/>
}
现在styled-component
很幸福。
推荐阅读
- angular5 - 我们可以在 Angular 5 中使用 Cropit 吗?
- c++ - Reading Message from MSMQ using C++
- typescript - 用于函数的 Typescript 继承和重载的字符串文字参数
- c# - RegisterInstance & TransientLifetimeManager,有可能吗?
- functional-programming - Coq 函数定义 `Definition Term := forall T: Type, term T.` 是什么意思?
- javascript - 如何默认显示工具提示而不在纯css中悬停
- excel - VBA - 创建字符串/哈希的唯一ID
- javascript - 表单动作不会被“必需的”输入打断
- node.js - TypeORM & PM2:无法在 Heroku 上运行应用程序
- javascript - Firestore orderBy timestamp desc 不起作用