在多个html元素中包含JSX属性

时间:2017-07-22 19:11:20

标签: typescript jsx

我有一些JSX属性,我想添加到其他多个元素。

我需要包含的示例:

class?: string;
id?: string;
style?: string;

示例元素:

namespace JSX {
    interface IntrinsicElements {
        element1: { att1: string; }
        element2: { att2: string; }
        element3: { att3: string; }
    }
}

它的行为应该是什么:

namespace JSX {
    interface IntrinsicElements {
        element1: { att1: string; class?: string; id?: string; style?: string; }
        element2: { att2: string; class?: string; id?: string; style?: string; }
        element3: { att3: string; class?: string; id?: string; style?: string; }
    }
}

有没有办法在不需要重复代码的情况下实现这一目标?

1 个答案:

答案 0 :(得分:0)

找到一个解决方案,使用|运算符可以合并两个接口。

这样,您可以为所有基本属性(例如,类,id,样式)定义接口,并将其与特定属性接口合并(例如{att1:string;})。

所以这是我的解决方案代码:

namespace JSX {
    interface BaseAttributes {
        class?: string;
        id?: string;
        style?: string;
    }
    interface IntrinsicElements {
        element1: BaseAttributes | { att1: string; }
        element2: BaseAttributes | { att2: string; }
        element3: BaseAttributes | { att3: string; }
    }
}