как передать реквизиты в react typescript

#javascript #reactjs #typescript

Вопрос:

Я работаю над приложением react typescript, в котором реагирую, если у меня есть массив продуктов, я могу сопоставить каждый продукт с компонентом, передав один продукт в качестве реквизита

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

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

Мне нужно сделать то же самое в react typescript, но я получаю эту ошибку

Тип «{ product: CartItemType; handleAddToCart: () => null;} » не может быть присвоен типу «Встроенные атрибуты и реквизиты» { дети?: 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;
 

Ответ №1:

Вашему Product компоненту необходимо знать список всех реквизитов, для этого вы можете создать отдельный тип:

 type Props = {
// your types here
}
 

После вы можете просто использовать этот тип:

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

Ответ №2:

Вам нужно добавить компонент «Тип для товара», чтобы принять товар реквизита, handleAddToCart. В компоненте вашего товара тип должен быть таким, как показано ниже:

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

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