我在React中有一个组件可以显示产品的分页。我无法弄清楚为什么在尝试运行应用程序时出现此错误:
React with TypeScript: Type '{ postsPerPage: number; totalPosts: number; paginate: (pageNumber: number) => void; }' is not assignable to type 'IntrinsicAttributes & ProductListProps'. Property 'postsPerPage' does not exist on type 'IntrinsicAttributes & ProductListProps'.
我的代码:
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = data.slice(indexOfFirstPost, indexOfLastPost);
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
return (
<>
<h1 className="headline">SHOP</h1>
<div className="total">Total: ${totalPrice}</div>
<ProductList products={data} onProductAddRequest={onProductAdded} posts={currentPosts}/>
<Pagin postsPerPage={postsPerPage} totalPosts={data.length} paginate={paginate} />
</>
我的组件看起来像这样:
interface PaginProps {
postsPerPage: number,
totalPosts: number,
paginate: (arg: number) => void
}
const Pagin = ( {postsPerPage, totalPosts, paginate}: PaginProps ) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil (totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
const pageNum = pageNumbers.map(number => {
return <div className='a page-item' key={number}><a className='a' onClick={() => paginate(number)} href="!#">{number}</a>
</div>
})
return (<div className='pagin'>{pageNum}</div>)
}
export default Pagin;
我的ProductListProps
看起来像这样:
interface ProductListProps {
products: ProductType[];
posts: any[];
onProductAddRequest: (product: ProductType) => void
}
interface ProductType {
id: number;
category: string;
images?: string[];
name: string;
price: number;
description?: string;
}
我在这里找不到问题
答案 0 :(得分:0)
我看不到您的组件中如何使用ProductListProps
,但是我认为发生此错误是因为您没有完全正确地键入您的组件。使用typescript的正确方法是使用React.FC
或React.FunctionalComponent
(假设您是最新的React版本之一),然后将接口声明为泛型类型。
interface PaginProps {
postsPerPage: number,
totalPosts: number,
paginate: (arg: number) => void
}
const Pagin: React.FC<PaginProps> = ({ postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil (totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
const pageNum = pageNumbers.map(number => {
return <div className='a page-item' key={number}><a className='a' onClick={() => paginate(number)} href="!#">{number}</a>
</div>
})
return (<div className='pagin'>{pageNum}</div>)
}
export default Pagin;