如何在反应打字稿中传递道具

时间:2021-03-11 16:37:32

标签: javascript reactjs typescript

我正在开发一个 react 打字稿应用程序, inn react 如果我有一系列产品,我可以通过将单个产品作为道具传递来将每个产品映射到一个组件

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

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

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

<块引用>

输入'{产品:CartItemType; handleAddToCart: () => null; }' 不是 可分配到类型 'IntrinsicAttributes & Props & { children?: 反应节点; }'。类型上不存在属性“产品” 'IntrinsicAttributes & Props & { children?: ReactNode; }'。 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;

2 个答案:

答案 0 :(得分:1)

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

type Props = {
// your types here
}

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

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

答案 1 :(得分:1)

需要为Item组件添加类型接受props产品,handleAddToCart。 在您的 Item 组件中,输入应如下所示:

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

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