问题
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