【问题标题】:How do I use a StyledComponent where React.Component is expected?如何使用带有 React.Component 的样式化组件?
【发布时间】:2021-01-19 19:33:15
【问题描述】:

我正在尝试创建一个 typescript React 应用程序,但在使用 styled-components 时遇到了问题。以下是我正在尝试的粗略想法:

import React from 'react';
import styled from 'styled-components';

export type MyProps = {
  wrapper?: React.Component,
};

const DefaultWrapper = styled.div`
  background: blue;
`;

const MyComponent = ({wrapper: Wrapper = DefaultWrapper}: MyProps) => {
  return <Wrapper className='my-wrapper'>
    Some child content
  </Wrapper>;
}

export default MyComponent;

当我尝试在另一个组件中渲染 MyComponent 时出现问题,因为它会引发错误,提示 JSX element type 'Wrapper' does not have any construct or call signatures

我想通过某种方式将样式化组件用作默认值或 wrapper 道具的有效值,这样就不会暴露我在内部使用样式化组件。任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    问题

    React.Component 是 React 类元素(不是类型),而是使用类型 React.ComponentType&lt;any&gt;。如果您正在使用组件类型约束并期望 wrapper 是某种类型的组件,则将 React.ComponentType&lt;any&gt; 替换为必要的约束——例如 React.ComponentClass&lt;any, any&gt; 用于基于类的组件或 React.FC&lt;any&gt;用于功能组件。

    解决方案

    import * as React from "react";
    import styled from "styled-components";
    
    export type MyProps = {
      wrapper?: React.ComponentType<any>;
    };
    
    const DefaultWrapper = styled.div`
      background: blue;
    `;
    
    const MyComponent = ({ wrapper: Wrapper = DefaultWrapper }: MyProps) => {
      return <Wrapper className="my-wrapper">Some child content</Wrapper>;
    };
    
    export default MyComponent;
    

    工作回购

    忽略'React' was used before it was defined. eslint 警告,这是一个代码框问题——在本地可以正常工作:

    【讨论】:

    • 谢谢,这正是我所需要的。我以为我只是在某个地方输入了不正确的类型,但不知道在哪里寻找我的错误。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2017-10-23
    • 2019-11-12
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多