【问题标题】:TypeScript Interface Issue with JSX.Element in ReactReact 中 JSX.Element 的 TypeScript 接口问题
【发布时间】:2021-10-30 23:04:03
【问题描述】:

我正在尝试在 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)

【问题讨论】:

  • 您的意思是const rows: RowsData[] = [...?即声明行的类型为RowData[], not RowsData.

标签: reactjs typescript typescript-typings


【解决方案1】:

您的输入需要更改为,

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>},
];

【讨论】:

  • 该死的...... facepalm 这就是你的大脑在编码数小时后死亡时会发生的事情。非常感谢。
  • 我想该休息一下了 :-)
  • 是的,我也这么认为;)顺便说一句,JSX.Element 和 React.ReactNode 有什么区别,为什么你使用 React.ReactNode?​​span>
  • 这应该会详细回答您的问题 - stackoverflow.com/questions/58123398/…
猜你喜欢
  • 2020-02-01
  • 2022-11-18
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2019-01-31
  • 2021-06-18
  • 1970-01-01
相关资源
最近更新 更多