繁体   English   中英

如何在反应 typescript 中传递道具

[英]how to pass props in react typescript

我正在开发一个反应 typescript 应用程序,如果我有一系列产品,我可以通过将单个产品作为道具传递给每个产品 map 每个产品到一个组件

 products = [{_id: 1, name: 'product1'},{_id: 1, name: 'product2'}{_id: 3, name: 'product3'}]

products.map(product => (<Product product={product} />)

我需要在反应 typescript 中做同样的事情,但我收到了这个错误

类型'{产品:CartItemType; handleAddToCart: () => null; }' 不可分配给类型 'IntrinsicAttributes & Props & { children?: ReactNode; }'。 'IntrinsicAttributes & Props & { children?: ReactNode; 类型上不存在属性 'product' }'。 TS2322

这是我的代码

    import { useState } from 'react';
import { useQuery } from 'react-query'
 
import Item from './item/item'


// Types
export type CartItemType = {
  id: number;
  category: string;
  description: string;
  image: string;
  price: number;
  title: string;
  amount: number;
}
 
const fetchProducts = async ():Promise<CartItemType[]> => {
  const res = await fetch("https://fakestoreapi.com/products");
  return res.json();
};


function App() { 
  const { data, isLoading, error, status } = useQuery<CartItemType[]>("products", fetchProducts);
  console.log(data); 
  
  const handleAddToCart = () => null;
  
  return (
    <div>
      {data?.map((product)=>( 
          // my error is on this line, product 
          <Item product={product} handleAddToCart={handleAddToCart}/> 
      )) 
      } 
    </div>
  );
}

export default App;

您的Product组件需要知道所有道具的列表,您可以为此创建一个单独的类型:

type Props = {
// your types here
}

之后你可以简单地使用这种类型:

export const Product: React.FC<Props> = props => { //your code here }

您需要添加 Item 组件的类型以接受道具产品,handleAddToCart。 在您的 Item 组件中,类型应如下所示:

interface ItemProps {
  product: CartItemType,
  handleAddToCart: () => null
}

export const Item = (props: ItemProps) => {
  // your Item component implementation
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM