[英]React abstract component (ES6) that renders an array of components. How to create a d.ts file for it?
我正在嘗試為下一個組件創建一個聲明文件。 它是用 JS ES6 編寫的。
function Column({ className, layout }) {
function renderLayout() {
return layout.map((item, index) => {
const Component = item?.component || item;
return (
<Component
{...item?.options}
// eslint-disable-next-line react/no-array-index-key
key={index}
/>
);
});
}
return (
<div className={className} >
{renderLayout()}
</div>
);
}
聲明示例:
<Column
className='test'
layout={[
{
component: Input, // It can use options
options: { // It can have a custom shape. How to define types for options?
first: 'test'
}
},
{
component: Date, // It can use options
options: { // It can have a custom shape. How to define types for options?
second: 'test',
newValue: { index: 3 }
}
}
]}
/>
<Column
className='test'
layout={[Input, Date]}
/>
我對選項屬性有疑問。 我不知道如何為對象定義類型,因為它可以有不同的類型,具體取決於用戶傳遞的組件。
Input , Date - 是組件的示例,它可以替換為任何其他組件。
我的聲明文件。
interface ILayout {
component?: React.ElementType;
options?: any; // <---- Here is a problem. How to replace any with defined types.
}
interface ColumnProps {
className?: string;
layout?: (ILayout|React.ElementType)[];
}
export class Column extends React.Component<ColumnProps> {}
您可以使ILayout
成為條件類型:
type ILayout = {
component?: InputType;
options?: OptionsForInputType
} | {
component?: DateType;
options?: OptionsForDateType
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.