[英]Type '() => JSX.Element' is not assignable to type 'ReactNode'
[英]Argument of type '(props: ITableProps) => JSX.Element' is not assignable to parameter of type … - React HOC
我有一個裝載機 HOC
特設:
const withLoader = <P extends object>(WrappedComponent: new () => React.Component<P, any>, loading: boolean) => {
return class WithLoading extends React.Component<P, any> {
render() {
return (
<div >
<div className={`${loading} ? 'loader' : '' "></div>
<WrappedComponent {...this.props} />
</div>
)
}
}
}
我以這種方式使用它,例如:
const TableHOC = withLoader(Table,true);
現在我的表或任何其他組件,例如,將有自己定義良好的道具接口。 一切都很好打字。
但是我遇到了這個問題
Argument of type '(props: ITableProps) => JSX.Element' is not assignable to parameter of type 'new () => Component<object, any, any>'.
Type '(props: ITableProps) => Element' provides no match for the signature 'new (): Component<object, any, any>'.ts(2345)
我該如何解決這個問題?
您需要使用React.ComponentType
作為類型:
const withLoader = <P extends object>(WrappedComponent: React.ComponentType<P>, loading: boolean) => {
// ...
}
不過請注意,如果您計划通過 state 更改來切換loading
值,您需要將其作為道具傳遞。 這是因為每次調用withLoader
來獲取增強組件時,它都是一個新組件,這意味着如果您在render
內部執行此操作,React 將始終卸載並重新安裝該渲染組件。 這也意味着增強組件內部的任何 state 都將丟失。
例如:
interface WithLoadingProps {
loading: boolean;
}
const withLoader = <P extends object>(
WrappedComponent: React.ComponentType<P>
) => {
return class WithLoading extends React.Component<P & WithLoadingProps, any> {
render() {
const { loading } = this.props;
return (
<div>
<div className={loading ? "loader" : ""}>
<WrappedComponent {...this.props} />
</div>
</div>
);
}
};
};
樣品用途:
const MyComponent = ({ text }: { text: string }) => {
return <div>{text}</div>;
};
const MyLoadingComponent = withLoader(MyComponent);
class Foo extends React.Component<{}, { loading: boolean }> {
render() {
const { loading } = this.state;
return <MyLoadingComponent loading={loading} text="foo" />;
}
}
最重要的是,還可以考慮按照 React 文檔中的說明添加displayName
- 這將增強您在使用 React 開發工具時的調試體驗。
和:
沒有:
interface WithLoadingProps {
loading: boolean;
}
const getDisplayName = <P extends object>(Component: React.ComponentType<P>) =>
Component.displayName || Component.name || "Component";
const withLoader = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
class WithLoading extends React.Component<P & WithLoadingProps, any> {
static readonly displayName = `WithLoading(${getDisplayName(WrappedComponent)})`;
render() {
const { loading } = this.props;
return (
<div>
<div className={loading ? "loader" : ""}>
<WrappedComponent {...this.props} />
</div>
</div>
);
}
}
return WithLoading;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.