【问题标题】:Styling a custom React styled-component in Typescript?在 Typescript 中为自定义 React 样式组件设置样式?
【发布时间】:2021-02-23 10:13:51
【问题描述】:

我有这个CustomScroll 组件。

CustomScroll.tsx

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

interface Container_DIV {
  className: string
}

const Container_DIV = styled.div<Container_DIV>`
  // SOME CCS PROPERTIES
`;

interface CustomScroll {
  className: string
}

const CustomScroll: React.FC<CustomScroll> = (props) => {
  console.log("Rendering CustomScroll...");

  return(
    <Container_DIV className={props.className}>
      {props.children}
    </Container_DIV>
  );
};

export default React.memo(CustomScroll);

请注意,我传递了 className 道具让 styled-components 做它的事情。

当我使用它时,我需要使用一些额外的属性来设置它的样式。

MyComponent.tsx

import styled from "styled-components";
import CustomScroll from "./Parts/CustomScroll";

const Filters_DIV = styled(CustomScroll)`
  // SOME CCS PROPERTIES
`;

我收到以下错误:

没有重载匹配这个调用。

重载 1 of 2, '(props: Pick & Partial>, "className"> & { theme?: DefaultTheme | undefined; } & { . ..; }): ReactElement<...>',出现以下错误。

类型'{孩子:元素; }' 与类型 'IntrinsicAttributes & Pick & Partial>, "className"> & { ...; 没有共同的属性} & { ...; }'。

Overload 2 of 2, '(props: StyledComponentPropsWithAs): ReactElement<...>',出现以下错误。

类型'{孩子:元素; }' 与类型 'IntrinsicAttributes & Pick & Partial>, "className"> & { ...; 没有共同的属性} & { ...; }'.ts(2769)

我做错了什么?

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    不完全确定出了什么问题,但似乎你需要传播的不仅仅是className 属性。

    所以我决定将完整的{...props} 对象传播到CustomScroll 组件中。

    注意:如果有人能解释出了什么问题,以及为什么需要完整的props,我很想知道这一点。

    这正在工作:

    CustomScroll.tsx

    import React from "react";
    import styled from "styled-components";
    
    interface Container_DIV {}  // THIS INTERFACE IS NOT BEING USED
    
    const Container_DIV = styled.div<Container_DIV>`
      // SOME CCS PROPERTIES
    `;
    
    interface CustomScroll {}   // THIS INTERFACE IS NOT BEING USED
    
    const CustomScroll: React.FC<CustomScroll> = (props) => {
      console.log("Rendering CustomScroll...");
    
      return(
        <Container_DIV {...props}>   {/* ALL PROPS ARE BEING SPREADED */}
          {props.children}
        </Container_DIV>
      );
    };
    
    export default React.memo(CustomScroll);
    

    MyComponent.tsx

    import styled from "styled-components";
    import CustomScroll from "./Parts/CustomScroll";
    
    const Filters_DIV = styled(CustomScroll)`
      // SOME CCS PROPERTIES
    `;
    

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2018-03-22
      • 2020-05-23
      • 2022-07-13
      • 2021-04-01
      • 2021-06-17
      相关资源
      最近更新 更多