How to add custom html attributes in JSX

后端 未结 11 1937
南方客
南方客 2020-11-27 18:14

There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?

11条回答
  •  爱一瞬间的悲伤
    2020-11-27 18:55

    Depending on what exactly is preventing you from doing this, there's another option that requires no changes to your current implementation. You should be able to augment React in your project with a .ts or .d.ts file (not sure which) at project root. It would look something like this:

    declare module 'react' {
        interface HTMLAttributes extends React.DOMAttributes {
            'custom-attribute'?: string; // or 'some-value' | 'another-value'
        }
    }
    

    Another possibility is the following:

    declare namespace JSX {
        interface IntrinsicElements {
            [elemName: string]: any;
        }
    }
    

    See JSX | Type Checking

    You might even have to wrap that in a declare global {. I haven't landed on a final solution yet.

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

提交回复
热议问题