如何正确定义样式组件的引用?
我写了下面的测试代码。这是一个精炼的代码,与之前的代码 (How to correctly define a reference (React.RefObject) for styled-components (for TypeScript)?) 不同。添加了引用类型 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>
);
}
}
行中出现错误:
<ModalShadowContainer ref={this.modalRef}>
错误文本:
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<{}, {}, {}>'.
如何在 TypeScript 语言中描述(定义)一个 ref?
最佳答案
也许这有帮助。
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>>();
关于reactjs - 如何正确定义样式组件(对于 TypeScript)的引用(React.RefObject<StyledComponentClass>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53113641/