How do I add attributes to existing HTML elements in TypeScript/JSX?

前端 未结 4 2163
栀梦
栀梦 2020-12-15 17:46

Anyone know how to properly add/extend all native HTML element attributes with custom ones?

With the TypeScript documentation for merging interfaces, I thought that

4条回答
  •  一整个雨季
    2020-12-15 18:17

    I wanted to use glamor's createElement replacement which adds a css prop to every element.

    To add to the accepted answer, module augmentation seems to do the trick but HTMLProps only worked for non-input elements. The correct interfaces to extend seems to be HTMLAttributes and SVGAttributes.

    declare module 'react' {
      interface HTMLAttributes {
        css?: any
      }
    
      interface SVGAttributes {
        css?: any
      }
    }
    

    To avoid importing the module augmentation in every component, re-export createElement:

    // createElement.ts
    import { createElement } from 'glamor/react'
    
    declare module 'react' {
      interface HTMLAttributes {
        css?: any
      }
    
      interface SVGAttributes {
        css?: any
      }
    }
    
    export default createElement
    

    Then tell TS to use our createElement for JSX with this tsconfig:

    {
      "compilerOptions": {
        "jsx": "react",
        "jsxFactory": "createElement"
      }
    }
    

    Usage:

    // MyComponent.tsx
    import createElement from './createElement'
    
    export default function MyComponent() {
      return 
    }

提交回复
热议问题