如何解决用泛型反应函数式 HOC
我知道这个问题已被问过多次,但我认为我的问题有所不同。我不想学习如何实现 HOC
,我已经这样做了(虽然还没有测试 :)),我的问题是使用它。
下面是我的HOC
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} />;
};
用BaseFunctionality导出默认值;
以及我如何尝试使用它
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);
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
知识。
解决方法
我想太多了,我需要做的就是像这样创建 TestPage
const TestPage = ({fetchItems}: TestProps) => {
并且所有错误都消失了,事实上,即使 HOC
中的逻辑也有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。