【问题标题】:How to use generic types correctly in HOC components?如何在 HOC 组件中正确使用泛型类型?
【发布时间】:2021-09-25 02:56:38
【问题描述】:

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

<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)。 我应该如何使用类型和泛型来消除这个错误?我试图阅读文档,但我不明白我做错了什么。

【问题讨论】:

  • 请分享可重现的例子
  • @captain-yossarian,它的重现性还不够吗?我可以添加什么来使问题更容易理解?
  • 尝试将代码从您的问题复制到任何沙箱
  • @captain-yossarian,对不起,做不到有几百个文件,而且所有的逻辑都是链接的,需要几个小时才能得到你需要的代码
  • 只分享最小可重现示例

标签: javascript reactjs typescript types high-order-component


【解决方案1】:

我认为这就是你想要达到的目标。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多