【问题标题】:Type error trying to pass an array of interfaces as a prop尝试将接口数组作为 prop 传递时出现类型错误
【发布时间】:2022-12-05 05:16:33
【问题描述】:

我正在尝试将存储在 useState 挂钩中的接口数组传递给子功能组件。

这是钩子。它仅在用户交互后才会填充:

  const [districtData, setDistrictData] = useState<DistrictData[]>([]);

这是导入到父 tsx 文件中的界面。

export interface DistrictData {
  lng: number,
  lat: number,
  id: string }

这是我将它传递给子组件的地方 &lt;ListOfSchools/&gt; 这是 TS 给出错误的行。

 <ListOfSchools districtData={districtData} />

这是子组件 ListOfSchools.tsx 的样子:

import { DistrictData } from "@utils/nces";

interface Props {
  propWhichIsArray: DistrictData[];
}

export const ListOfSchools: React.FC<Props> = ({ propWhichIsArray }) => {
  return <div></div>;
};

这是我收到的错误:

Type '{ districtData: DistrictData[]; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
  Property 'districtData' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.

我相信目标是将道具设置为子组件期望的类型。

我也在下面尝试过,以及来自 stackoverflow 文章的许多其他尝试:

export const ListOfSchools: React.FC<DistrictData[]> = ({ props: DistricData[] }) => {
  return <div></div>;
}; 

非常感谢您在这里提供的任何帮助。

【问题讨论】:

    标签: reactjs typescript interface


    【解决方案1】:

    根据您提供的代码,您似乎正试图将 districtData 道具传递给 ListOfSchools 组件,但您正试图在子组件中以 propWhichIsArray 的身份访问它。

    要修复您收到的错误,您需要确保您在子组件中使用的 prop 名称与您从父组件传递的 prop 名称相匹配。在这种情况下,您可以在传递它时更改父组件中的 prop 名称,如下所示:

    <ListOfSchools propWhichIsArray={districtData} />
    

    或者,您可以更改子组件中 prop 的名称以匹配传递给它的名称并相应地更新类型,如下所示:

    import { DistrictData } from "@utils/nces";
    
    interface Props {
      districtData: DistrictData[];
    }
    
    export const ListOfSchools: React.FC<Props> = ({ districtData }) => {
      return <div></div>;
    };
    

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2017-04-26
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多