reactjs - ایجاد یک تابع تایپاسکریپت که کلاس کامپوننت ریاکت را بازگرداند
من نیاز دارم یک تابع کمکی ایجاد کنم که بسته به یک شرایط، یکی از کلاسهای کامپوننت React را برگرداند (نه نمونهها). بنابراین نوع بازگشتی تابع باید جنریک باشد (React.PureComponent)
import React from 'react';
class FooOne extends React.PureComponent {
render(): React.ReactElement {
return null;
}
}
class FooTwo extends React.PureComponent {
render(): React.ReactElement {
return null;
}
}
function getFooClass(condition: boolean): typeof React.PureComponent {
return condition ? FooOne : FooTwo;
}
const SomeFooClass = getFooClass(true);
const instance: React.PureComponent = new SomeFooClass();
کد بالا به نظر میرسد که کار میکند (من هنوز نمیفهمم چرا باید از typeof React.PureComponent به عنوان نوع بازگشتی برای getFooClass استفاده کنم، این موضوع به صورت تجربی کشف شد)، اما تایپاسکریپت خطای زیر را برای getFooClass تولید میکند:
Type 'typeof FooOne' is not assignable to type 'typeof PureComponent'.
Construct signature return types 'FooOne' and 'PureComponent<P, S>' are incompatible.
The types of 'props' are incompatible between these types.
Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly<{ children?: ReactNode; }> & Readonly<P>'.
Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly<P>'.
شاید این نوعی باگ یا محدودیت تایپاسکریپت باشد؟
پاسخ شماره ۱
چیزی شبیه امتحان کن
function getFooClass(condition: boolean): React.ComponentType {
// if FooOne and FooTwo have arguments you can use React.ComponentType<TArgs>
return condition ? FooOne : FooTwo;
}
استفاده باید به این صورت باشد
function render() {
const FooEl = getFooClass(true); // PascalCase is required
return <FooEl />
}
یا به سادگی نمونه ایجاد شده را بازگردانید
function getFooClass(condition: boolean): JSX.Element {
return condition ? <FooOne /> : <FooTwo />;
}
پاسخ شماره ۲
React.ReactNode باید در این مورد کار کند:
function getFooClass(condition: boolean): React.ReactNode {
return condition ? FooOne : FooTwo;
}
