繁体   English   中英

将具有给定属性的对象值显示为子项会产生错误 - React 和 Typescript

[英]Displaying object values with given properties as children gives error - React and Typescript

我试图在<th><td>标记内显示具有给定属性的对象值,但它会导致错误Type '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)} {object ? object[key] : firstLetterUppercase(key as string)} with <></>? 这是代码... return ( <ChosenTag key={key as string}> {/* 这是错误 */} <> {object ? object[key] : firstLetterUppercase(key as string)} </> ) ; 我希望这可以帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM