2

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

我找不到这里有什么问题

4

1 回答 1

5

我看不到ProductListProps您的组件中是如何使用的,但我认为发生错误是因为您没有完全正确地键入您的组件。使用 typescript 的正确方法是使用React.FCor 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;
于 2019-12-11T17:30:17.530 回答