显示带有给定属性的对象值会导致错误- React和Typescript



我试图在<th><td>标签内显示给定属性的对象值,但会导致错误类型'string | ObjectType[keyof ObjectType]'不可分配给类型'ReactNode'。。但奇怪的是,当我console.log(object[key])时,一切都很正常。

代码如下:

interface Props<ObjectType> {
objects: ObjectType[];
properties: {
key: keyof ObjectType;
}[];
navigation?(id: number, item?: {}): void;
children?: boolean;
}
const DisplayTable = <ObjectType extends { id: number }>(props: Props<ObjectType>) => {
const { objects, properties, navigation, children } = props;
const displayKeys = (tag: 'th' | 'td', object: ObjectType): JSX.Element[] => {
return properties.map((propertie) => {
const { key } = propertie;
const ChosenTag = `${tag}` as keyof JSX.IntrinsicElements;
console.log(object[key]); //Works perfectly
return (
<ChosenTag key={key as string}>
{/* Here is the error */}
{object ? object[key] : firstLetterUppercase(key as string)}
</ChosenTag>
);
});
};
return (
......
)
}

你试过用<>来包装{object ? object[key] : firstLetterUppercase(key as string)}吗?这里是代码…回报({/*这里是错误*/}& lt;比;{对象?object[key]: firstLetterUppercase(key为字符串)}& lt;/比;(;我希望这能帮到你。

最新更新