属性“data”在类型“IntrinsicAttributes & Product[]”上不存在。这里有什么问题。React + 打字稿

Property 'data' does not exist on type 'IntrinsicAttributes & Product[]'. What is the problem here. React + Typescript

提问人:AnubisTyrant 提问时间:11/14/2023 更新时间:11/14/2023 访问量:25

问:

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

该错误源于“Testing”函数调用声明。我不知道问题出在哪里。我试着搜索一下,但想不通。我是初学者。

我尝试从打字稿操场运行代码,它运行良好。但这是一个 React + Typescript 环境,它向我显示错误。

reactjs 打字稿 react-typescript

评论


答:

0赞 257bit 11/14/2023 #1

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

function Testing({ data }: { data: Product[] }) {
  return <p>{data[0].category}</p>;
}
0赞 Tal Rofe 11/14/2023 #2

这不是将 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 作为约定。然后,您可以通过访问属性名称来访问该值。