【发布时间】:2021-04-13 13:23:42
【问题描述】:
我是新来的。如果我把我的问题命名错了,我很抱歉。
我想创建一个 React 组件,该组件将根据给它的 prop 更改图像源。
我被一些代码卡住了。
<CustomIcon type={'tooth'} />
这是一个 CustomIcon 组件的内部
import React from 'react';
import { CustomIconProps } from './CustomIcon.types';
import { Img } from './CustomIcon.styles';
import iconPath from '../../assets/icons/iconPath';
export const CustomIcon: React.FC<CustomIconProps> = props => {
return <Img src={iconPath[props.type]} />;
};
这是CustomIcon.types.ts的内部
export type CustomIconProps = {
type: string;
};
这是iconPath.ts的内部
import tooth from './tooth.png';
const iconPath = {
tooth: tooth,
};
export default iconPath;
这是我的错误:
TypeScript error in /home/buashei/work/reservation_module/src/components/CustomIcon/CustomIcon.tsx(15,20):
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Toot'.
No index signature with a parameter of type 'string' was found on type 'Toot'. TS7053
13 |
14 | export const CustomIcon: React.FC<CustomIconProps> = props => {
> 15 | return <Img src={iconPath[props.type]} />;
| ^
16 | };
17 |
请告诉我应该在哪里以及如何为“牙齿”添加类型。
在此先感谢您对这个问题的帮助,这让我大吃一惊
【问题讨论】:
-
您的错误涉及
Toot- 是另一个组件还是拼写错误? -
@DeanJames
Toot是 iconPath 对象中的键和值。但我找到了解决我的问题的方法。export interface IconPathProps extends Record<string, string> { tooth: string; }
标签: reactjs typescript typescript-typings styled-components