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

≡放荡痞女 提交于 2019-12-23 17:30:35

问题


How to correctly define a reference for styled-components?

I wrote the following test code:

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

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

export default class Modal extends Component {

    private modalRef: RefObject<HTMLDivElement>;

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

    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<HTMLDivElement>' is not assignable to type 'string | (string & ((instance: HTMLDivElement | null) => any)) | (string & RefObject<HTMLDivElement>) | (((instance: Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, any>, any, any> | null) => any) & string) | ... 5 more ... | undefined'.
  Type 'RefObject<HTMLDivElement>' is not assignable to type 'RefObject<Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, any>, any, any>> & RefObject<HTMLDivElement>'.
    Type 'RefObject<HTMLDivElement>' is not assignable to type 'RefObject<Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, any>, any, any>>'.
      Type 'HTMLDivElement' is not assignable to type 'Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, any>, any, any>'.
        Property 'setState' is missing in type 'HTMLDivElement'.

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

来源:https://stackoverflow.com/questions/53103497/how-to-correctly-define-a-reference-react-refobject-for-styled-components-for

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