How to correctly define a reference (React.RefObject<StyledComponentClass>) for styled-components (for TypeScript)?

牧云@^-^@ 提交于 2019-12-05 02:01:46

问题


How to correctly define a reference for styled-components?

I wrote the following test code. This is a refined code, unlike the previous one (How to correctly define a reference (React.RefObject) for styled-components (for TypeScript)?). Added reference type StyledComponentClass< {}, any>.

import React, {Component, RefObject, ReactNode} from 'react';
import styled, {StyledComponentClass} from 'styled-components';

type TModalShadowContainer = StyledComponentClass<{}, any>;

const ModalShadowContainer: TModalShadowContainer = styled.div` 
    background-color: black;
`;

export default class Modal extends Component {

    private readonly modalRef: RefObject<TModalShadowContainer>;

    constructor(props: {}) {
        super(props);
        this.modalRef = React.createRef<TModalShadowContainer>();
    }

    public render(): ReactNode {
        return (
            <ModalShadowContainer ref={this.modalRef}>
                {this.props.children}
            </ModalShadowContainer>
        );
    }

}

The error appears on the line:

<ModalShadowContainer ref={this.modalRef}>

Error text:

Type 'RefObject<StyledComponentClass<{}, {}, {}>>' is not assignable to type 'string | ((instance: Component<{ as?: string | ComponentClass<any, any> | StatelessComponent<any> | undefined; theme?: {} | undefined; }, any, any> | null) => any) | RefObject<Component<{ ...; }, any, any>> | undefined'.
  Type 'RefObject<StyledComponentClass<{}, {}, {}>>' is not assignable to type 'RefObject<Component<{ as?: string | ComponentClass<any, any> | StatelessComponent<any> | undefined; theme?: {} | undefined; }, any, any>>'.
    Type 'StyledComponentClass<{}, {}, {}>' is not assignable to type 'Component<{ as?: string | ComponentClass<any, any> | StatelessComponent<any> | undefined; theme?: {} | undefined; }, any, any>'.
      Property 'setState' is missing in type 'StyledComponentClass<{}, {}, {}>'.

How to describe (define) a ref in TypeScript lang?


回答1:


Maybe this helps.

type MamkinHackerType<T> = T extends StyledComponentClass<React.DetailedHTMLProps<React.HTMLAttributes<infer ElementType>, infer ElementType>, infer T, infer H>
  ? ElementType & React.Component<React.DetailedHTMLProps<React.HTMLAttributes<ElementType>, ElementType> & T & H>
  : never
;

private readonly modalRef = React.createRef<MamkinHackerType<typeof ModalShadowContainer>>();


来源:https://stackoverflow.com/questions/53113641/how-to-correctly-define-a-reference-react-refobjectstyledcomponentclass-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!