如何正确定义样式组件的引用(React.RefObject<StyledComponentClass>)(对于 TypeScript)?
Posted
技术标签:
【中文标题】如何正确定义样式组件的引用(React.RefObject<StyledComponentClass>)(对于 TypeScript)?【英文标题】:How to correctly define a reference (React.RefObject<StyledComponentClass>) for styled-components (for TypeScript)? 【发布时间】:2019-04-06 09:46:17 【问题描述】:如何正确定义样式组件的引用?
我编写了以下测试代码。这是一个精炼的代码,与前一个 (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?
【问题讨论】:
【参考方案1】:也许这会有所帮助。
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>>();
【讨论】:
你在哪里找到这个解决方案? 只看想要获取 ts-compiler 的类型,并用 TypeScript 条件类型“推断”它。 但我认为这不是一个好的解决方案。我们需要对 react/styled-componets 类型进行全面改进。 Спасибо заответ! Для меня это пока высший полет)以上是关于如何正确定义样式组件的引用(React.RefObject<StyledComponentClass>)(对于 TypeScript)?的主要内容,如果未能解决你的问题,请参考以下文章