【问题标题】:TypeScript types for React component where prop is an array of objects?React 组件的 TypeScript 类型,其中 prop 是对象数组?
【发布时间】:2020-01-12 13:09:48
【问题描述】:

我的 React 组件有一个名为 propWhichIsArray 的 prop,它将是一个对象数组。这些对象将有一个 id 这是一个 ID 和 text 这是一个字符串。你怎么能用 TypeScript 输入这个?

type Props = {
  propWhichIsArray: {
    id,
    text: string;  
  }[]
};

const Component: React.FC<[Props]> = ({ propWhichIsArray }) => {
  //

我收到一个错误:

类型 '[Props] & { children? 上不存在属性 'propWhichIsArray': 反应节点; }'。 TS2339

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    主要问题是您正在使用React.FC&lt;[Props]&gt; 而不是React.FC&lt;Props&gt;。使用方括号,您将创建一个 tuple 类型,其第零个元素的类型为 Props,然后您将该元组作为组件的 props。此外,我可能会将道具指定为接口。

    interface Props {
      propWhichIsArray: {
        id: ID; // I assume ID is defined elsewhere
        text: string;
      }[]
    }
    
    const Component: React.FC<Props> = ({ propWhichIsArray }) => {
    

    如果数组中的这个数据在其他地方被使用,你可能想把它拉出来到它自己的接口:

    interface Thingamajig {
      id: ID;
      text: string;
    }
    
    interface Props {
      propWhichIsArray: Thingamajig[];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 2020-05-27
      • 2021-09-11
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多