首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Functional HOC with Generics

React Functional HOC with Generics
EN

Stack Overflow用户
提问于 2021-06-06 21:21:21
回答 1查看 36关注 0票数 0

我知道这个问题已经被问了很多次,但我认为我的问题是不同的。我不想学习如何实现HOC,我已经做到了(虽然还没有测试:),我的问题是使用它。

下面是我的HOC

代码语言:javascript
复制
const withBaseFunctionality =
<T extends BaseModel, P extends BaseProps<T>>(
WrappedComponent: FunctionComponent<P>
) =>
(props: P) => {
//States
const [page, setPage] = useState(1);

//Update props
const updatedProps = produce(props, (draftProps) => {
  draftProps.handlePageChange = handlePageChange;
  draftProps.fetchItems = fetchItems;
  draftProps.handleCreateItem = handleCreateItem;
  draftProps.handleUpdateItem = handleUpdateItem;
  draftProps.handleDeleteItem = handleDeleteItem;
});

//API
const fetchItems = useItems(props.subPath, page - 1);
//Handles all the create logic
const handleCreateItem = (item: T) => {};

//Handles all the update logic
const handleUpdateItem = (item: T) => {};

//Handles all the delete logic
const handleDeleteItem = (item: T) => {};

//Handles page changes
const handlePageChange = (page: number) => setPage(page);

return <WrappedComponent {...updatedProps} />;
};

导出默认withBaseFunctionality;

以及我是如何尝试使用它的

代码语言:javascript
复制
interface TestModel extends BaseModel{
name: string;
acronym: string;   
}


interface TestProps extends BaseProps<TestModel>{


}


const TestPage: FunctionComponent<TestProps>  = ({}) => {


return<></>;

}

export default withBaseFunctionality(TestPage);

我在这行export default withBaseFunctionality(TestPage);上得到了下面的错误

代码语言:javascript
复制
Argument of type 'FunctionComponent<TestProps>' is not assignable to parameter of type 
'FunctionComponent<BaseProps<BaseModel>>'.
Types of property 'propTypes' are incompatible.
Type 'WeakValidationMap<TestProps> | undefined' is not assignable to type 
'WeakValidationMap<BaseProps<BaseModel>> | undefined'.
  Type 'WeakValidationMap<TestProps>' is not assignable to type 
'WeakValidationMap<BaseProps<BaseModel>>'.
    Types of property 'handleCreateItem' are incompatible.
      Type 'Validator<(item: TestModel) => void> | undefined' is not assignable to type 
'Validator<(item: BaseModel) => void> | undefined'.
        Type 'Validator<(item: TestModel) => void>' is not assignable to type 
'Validator<(item: BaseModel) => void>'.
          Type '(item: TestModel) => void' is not assignable to type '(item: BaseModel) => 
 void'.ts(2345)

请注意,我不太擅长Typescript or JS,我正在使用我的Java知识。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-06 21:57:57

我过多地考虑了应用程序,我所需要做的就是像这样创建TestPage const TestPage = ({fetchItems}: TestProps) => {,然后所有的错误都消失了,事实上,甚至HOC中的逻辑也是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67859598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档