gpt4 book ai didi

javascript - 如何在 HOC 组件中正确使用泛型类型?

转载 作者:行者123 更新时间:2023-12-04 17:17:14 26 4
gpt4 key购买 nike

这是我的父组件(Grid),(这里我传递了更多 hoc 使用的 Prop ,但我在这里省略了它们):

<QuickBooksTable itemList={quickBooksList} />
这是表组件:
export const QuickBooksTable = withIntegrationTable(props: : WithIntegrationTableChildProps & WithIntegrationTableProps) => ...
这是特别的:
export function withIntegrationTable<T extends WithIntegrationTableProps>(Component: React.ComponentType<T>) {
return (
{
itemList,
...props
}: WithIntegrationTableProps & T
) => {
const [state, setState] = useState<WithIntegrationTableState>({
tableItems: new Array<any>(),
selectedItems: new Set<string>(),
isAllItemsSelected: false
});

useEffect(() => {
const tableItems = mapItemList(itemList, currentUser);
setState({
...state,
tableItems
});
}, [itemList]);

<Component {...props as T}
tableState={state}
/>
}
}
但是当它编译时它说: Element QuickBooksTable doesn't have required attribute (here is another props name) .
我应该如何使用类型和泛型来消除这个错误?我试图阅读文档,但我不明白我做错了什么。

最佳答案

我认为这就是你试图实现的目标。

import React from 'react';
import { useEffect, useState } from 'react';

interface WithIntegrationTableProps {
itemList: string[]
}

interface WithIntegrationTableState { }

export const withIntegrationTable = <P extends WithIntegrationTableState>(
Component: React.ComponentType<P & {
tableState: WithIntegrationTableState
}>
): React.FC<P & WithIntegrationTableProps> => ({
itemList,
...props
}: WithIntegrationTableProps) => {
const mapItemList = (itemList: any, currentUser: any) => {

}

const [state, setState] = useState<WithIntegrationTableState>({
tableItems: new Array<any>(),
selectedItems: new Set<string>(),
isAllItemsSelected: false
});

useEffect(() => {
const tableItems = mapItemList(itemList, null);
setState({
...state,
tableItems
});
}, [itemList]);

return <Component {...props as P} tableState={state} />
}

export const QuickBooksTable = withIntegrationTable(({ ...props }) => {
console.log(props.tableState)
return <div>
test
</div>
})

const App = () => {
return <QuickBooksTable itemList={[]} />
}

export default App

关于javascript - 如何在 HOC 组件中正确使用泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68406704/

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