我是TypeScript的新手,我想将它与React一起使用。我有一个需要像这样导出的功能组件:
df1 <- structure(list(country = c("g", "g", "g", "g", "g"), regionarc = c("dome",
NA, NA, NA, NA), regionarb = c(NA, NA, "gongo", NA, NA), regionarh = c(NA,
"ashi", NA, NA, NA), regionary = c(NA, NA, NA, NA, NA), regionard = c(NA,
NA, NA, "salgi", NA), regionarw = c(NA, NA, NA, NA, "forh")),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
和import React from 'react';
import HOC from './HOC';
interface PropsType {
someProp: boolean;
}
const MyFunctionalComponent: React.FC<PropsType> = ({ someProp }) => {
return(
...
)
};
export default HOC(MyFunctionalComponent);
是这样的:
HOC.tsx
问题是我遇到以下错误,我已经用谷歌搜索,但没有找到明确的解决方案:
import React, { Suspense } from 'react';
import Loader from './Loader';
export default function HOC(HocComponent: React.FC) {
return function () {
return (
<Suspense fallback={<Loader />}>
<HocComponent />
</Suspense>
);
};
}
很明显,如果我不将Type '{ someProp: true; }' is not assignable to type 'IntrinsicAttributes'.
Property 'someProp' does not exist on type 'IntrinsicAttributes'. TS2322
用MyFunctionalComponent
包装,那么它可以正常工作。解决此问题的正确方法是什么?预先感谢。
答案 0 :(得分:1)
问题在于您必须将属性强制转换为抽象参数,例如object
。
这应该有效:
import React, { Suspense } from 'react';
import Loader from './Loader';
const withLoading<P extends object> (Component: React.ComponentType<P>) =>
class WithLoading extends React.Component<P> {
render() {
return (
<Suspense fallback={<Loader />}>
<HocComponent {...this.props as P} />
</Suspense>
);
}
}
}
export default HOC;
然后您可以简单地:
import React from 'react';
import withLoading from './HOC';
interface PropsType {
someProp: boolean;
}
const MyFunctionalComponent: React.FC<PropsType> = ({ someProp }) => {
return(
...
);
};
export default withLoading(MyFunctionalComponent);
以下是来源:https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb