javascript - TypeScript 错误:类型“字符串”不可分配给排版的类型
问题描述
我正在尝试将 Material-ui 中的 Typography 组件与 TypeScript 一起使用,但我收到了这个奇怪的错误
TypeScript error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLElement>, any> | FunctionComponent<HTMLAttributes<HTMLElement>> | undefined'. TS2322
8 | }
9 | export default ({ text, date }: Props) => (
> 10 | <Typography component="p" gutterBottom>
| ^
11 | {text && <span>{text}: </span>}
12 | <FormattedDate value={date} />
13 |
这是我的组件的样子
import React from 'react';
import { FormattedDate, FormattedTime } from 'react-intl';
import Typography from '@material-ui/core/Typography';
interface Props {
date: Date;
text?: string;
}
export default ({ text, date }: Props) => (
<Typography component="p" gutterBottom>
{text && <span>{text}: </span>}
<FormattedDate value={date} />
<FormattedTime value={date} />
</Typography>
);
我无法理解为什么道具"p"
的价值不可接受。component
我尝试使用"h1"
and "h2"
以同样的方式失败,显然,官方演示也使用了字符串。
有什么我遗漏的吗?,我不想用 忽略这个// @ts-ignore
,但想解决这个问题。
解决方案
如果在 2021 年发生这种情况,问题是我正在传播HTMLAttributes
针对 的输入InputBase
,而我应该正确传播InputBaseProps
。
在我的例子中,它与输入相关,但可以为每个组件复制相同的内容:只要您使用材质 UI 组件,您应该提供它要求的属性,并在使用/扩展它们时正确设置正确的道具类型。
给出错误的示例:
import { HTMLAttributes } from 'react';
import InputBase from '@material-ui/core/InputBase';
import inputStyle from 'Input.module.scss';
export interface InputProps extends HTMLAttributes<HTMLInputElement> {
}
export function Input(props: InputProps) {
const { ...rest } = props;
return (
<InputBase
fullWidth={true}
className={[inputStyle.input].join(' ')}
color='primary'
{...rest}
/>
);
}
(在这种情况下,出现了错误color
)
正确的方法:
import InputBase, { InputBaseProps } from '@material-ui/core/InputBase';
import inputStyle from 'Input.module.scss';
export interface InputProps extends InputBaseProps {
}
export function Input(props: InputProps) {
const { ...rest } = props;
return (
<InputBase
fullWidth={true}
className={[inputStyle.input].join(' ')}
color='primary'
{...rest}
/>
);
}
推荐阅读
- python - 如何根据列将 numpy 数组拆分为 numpy 数组?
- python - 如何获取不同列表的相同索引并将其放入单独的列表中?
- docker - RabbitMQ pod web 用户名和密码?
- python - 如何在不丢失曲线自然对数的情况下找到值
- c++ - 无法使用地图
除非我为 Custom_Class 定义没有参数的默认构造函数 - python - Keras 中的 flow_from_directory 方法是否会调整图像的大小,即使它们已经匹配所需的大小?
- cakephp - 如何在 cakephp 3.x 中使用子域
- sas - 如何按开始日期/结束日期对的时间顺序排列 SAS 数据集
- r - 如何在 R 中 ggplot2 的时间序列图中自定义离散时间步并将其添加到 x 轴?
- android - 在使用 Android Gradle 插件 3.6.2 进行注释处理期间,Android R 类不可用