reactjs - 如何正确定义样式组件(对于 TypeScript)的引用(React.RefObject<StyledComponentClass>)?

标签 reactjs typescript styled-components

如何正确定义样式组件的引用?

我写了下面的测试代码。这是一个精炼的代码,与之前的代码 (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/

相关文章:

javascript - 无法使用 typescript 创建 react 应用程序

带有 styled-components parent prop 的 react-native

reactjs - 样式组件中的条件渲染

javascript - React/Styled-Components : Need to hand roll a dropdown with multiple versions that a developer could use by passing a type in

html - 如何在没有id或class的输入字段中添加CSS?

javascript - spread 方法对对象有效吗?你如何复制一个对象?

javascript - ionic 2 中的菜单

reactjs - 切换选项卡时 react 查询突变 isLoading 变为 false

reactjs - 为什么在条形图中不显示 Y 轴,也不显示图表中 X 轴的所有标签?

TypeScript 文件中的 JavaScript 智能感知