首页 > 解决方案 > React 中 JSX.Element 的 TypeScript 接口问题

问题描述

我正在尝试在 React 中为数组创建一个类型,但出现以下错误。我不确定我在这里缺少什么。

谁能帮我找出我错过的东西?

谢谢

interface RowsData {
  [key: string]: string | number | JSX.Element;
}

const rows: RowsData = [
  { id: 1, name: 'A', action: <div style={{ color: 'blue' }}> Hello </div> },
  { id: 2, name: 'B', action: <div style={{ color: 'blue' }}> World </div> },
  { id: 3, name: 'C', action: <div style={{ color: 'blue' }}> Foo </div> }
];

错误

Type '{ id: number; name: string; action: JSX.Element; }' is not assignable to type 'string | number | Element'.
  Object literal may only specify known properties, and 'id' does not exist in type 'Element'.ts(2322)

标签: reactjstypescripttypescript-typings

解决方案


您的输入需要更改为,

interface Row {
  id: number;
  name: string;
  action: React.ReactNode;
}

const rows: Row[] = [
  {id: 1, name: 'A', action: <div style={{color: 'blue'}}> Hello </div>},
  {id: 2, name: 'B', action: <div style={{color: 'blue'}}> World </div>},
  {id: 3, name: 'C', action: <div style={{color: 'blue'}}> Foo </div>},
];


推荐阅读