[英]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.