Extending HTML elements in React and TypeScript while preserving props

后端 未结 6 1106
星月不相逢
星月不相逢 2021-02-04 23:58

I just can\'t wrap my head around this I guess, I\'ve tried probably half a dozen times and always resort to any... Is there a legitimate way to start with an HTML

6条回答
  •  梦毁少年i
    2021-02-05 00:16

    I encountered the same issue today and here is how I fixed it:

    ReactButtonProps.ts

    import {
      ButtonHTMLAttributes,
      DetailedHTMLProps,
    } from 'react';
    
    /**
     * React HTML "Button" element properties.
     * Meant to be a helper when using custom buttons that should inherit native "

    Usage in Button-ish component:

    import classnames from 'classnames';
    import React, { ReactNode } from 'react';
    import { ReactButtonProps } from '../../types/react/ReactButtonProps';
    
    type Props = {
      children: ReactNode;
      className?: string;
      mode?: BtnMode;
      transparent?: boolean;
    } & ReactButtonProps;
    
    
    const BtnCTA: React.FunctionComponent = (props: Props): JSX.Element => {
      const { children, className, mode = 'primary' as BtnMode, transparent, ...rest } = props;
      
      // Custom stuff with props
    
      return (
        
      );
    };
    
    export default BtnCTA;
    

    Usage:

     console.log('click')}>
      
      {modChatbot?.homeButtonLabel}
    
    

    I can now use onClick because it's allowed due to extending from ReactButtonProps, and it's automatically forwarded to the DOM through the ...rest.

提交回复
热议问题