reactjs 属性'data'在类型'IntrinsicAttributes & Product[X]'上不存在,这里有什么问题,React + Typescript

zzoitvuj  于 2023-11-18  发布在  React
关注(0)|答案(2)|浏览(142)

App.tsx

export default function FilterableProductTable() {
  const products: Product[] = [
    { category: "Fruits", price: "$1", stocked: true, name: "Apple" },
    { category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit" },
    { category: "Fruits", price: "$2", stocked: false, name: "Passionfruit" },
    { category: "Vegetables", price: "$2", stocked: true, name: "Spinach" },
    { category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin" },
    { category: "Vegetables", price: "$1", stocked: true, name: "Peas" },
  ];
  return (
    <>
      <Testing data={products} />
    </>
  );
}

interface Product {
  category: string;
  price: string;
  stocked: boolean;
  name: string;
}

function Testing(data: Product[]) {
  return <p>{data[0].category}</p>;
}

字符串
这个错误来自“测试”函数调用声明。我不知道是什么问题。我试着搜索它,但不能弄清楚。我是初学者。
我试着从一个typescript playground运行代码,它工作得很好。但是这是一个React + Typescript环境,它显示了错误。

myss37ts

myss37ts1#

TypeScript期望定义prop data,但是,您没有定义prop,而是直接访问data,就像它是一个prop一样。

function Testing({ data }: { data: Product[] }) {
  return <p>{data[0].category}</p>;
}

字符串

y0u0uwnf

y0u0uwnf2#

这不是你传递props给组件的方式。你应该这样做:

export default function FilterableProductTable() {
  const products: Product[] = [
    { category: "Fruits", price: "$1", stocked: true, name: "Apple" },
    { category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit" },
    { category: "Fruits", price: "$2", stocked: false, name: "Passionfruit" },
    { category: "Vegetables", price: "$2", stocked: true, name: "Spinach" },
    { category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin" },
    { category: "Vegetables", price: "$1", stocked: true, name: "Peas" },
  ];
  return (
    <>
      <Testing data={products} />
    </>
  );
}

interface Product {
  category: string;
  price: string;
  stocked: boolean;
  name: string;
}

interface Props {
  data: Product[];
}

function Testing(props: React.PropsWithChildren<Props>) {
  return <p>{props.data[0].category}</p>;
}

字符串
一般来说,当你通过自定义属性传递数据到你的组件时,数据会通过它的键值存储在组件函数参数中,我们习惯性的称之为props。然后你就可以通过访问属性名来访问值。

相关问题