TypeScript workaround for rest props in React

前端 未结 6 775
迷失自我
迷失自我 2021-02-06 22:50

Updated for TypeScript 2.1

TypeScript 2.1 now supports object spread/rest, so no workarounds are needed anymore!


Original Question

TypeScript s

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 23:00

    React.HtmlAttributes in the example above is now generic so I needed to extend from React.AnchorHTMLAttributes.

    Example:

    import React from 'react';
    
    type  AClickEvent = React.MouseEvent;
    
    interface LinkPropTypes extends React.AnchorHTMLAttributes {
        to: string;
        onClick?: (x: AClickEvent) => void;
    }
    
    class Link extends React.Component {
      public static defaultProps: LinkPropTypes = {
        to: '',
        onClick: null,
      };
    
    private handleClick = (event: React.MouseEvent) => {
       ...
        event.preventDefault();
        history.push(this.props.to);
     };
    
      public render() {
        const { to, children, ...props } = this.props;
        return (
          
            {children}
          
        );
        }
    }
    
    export default Link;
    

提交回复
热议问题