gpt4 book ai didi

javascript - 与 TypeScript react : Type is not assignable to type 'IntrinsicAttributes'

转载 作者:行者123 更新时间:2023-12-01 21:51:47 25 4
gpt4 key购买 nike

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

我找不到这里的问题

最佳答案

我没有看到 ProductListProps 是如何在你的组件中使用的,但我认为错误的发生是因为你没有完全正确地输入你的组件。使用 typescript 的正确方法是使用 React.FCReact.FunctionalComponent(假设您是最新的 React 版本之一),并声明接口(interface)作为通用类型。

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;

关于javascript - 与 TypeScript react : Type is not assignable to type 'IntrinsicAttributes' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59286815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com