【问题标题】:How to type extended styled-component?如何键入扩展样式组件?
【发布时间】:2018-10-05 01:23:06
【问题描述】:

Typescript@2.8.1styled-components@2.4.0

我需要有一个基本样式组件,该组件将被 .extend()ed 创建新的类似的组件,以避免代码重复。

我想出了以下不会引发任何错误的代码:

export interface Aprops {
  icon?: string;
}

export const A = styled<Aprops, 'div'>('div')`
  padding: ${(props) => (props.icon ? '10px' : '4px')};
`;

export interface Bprops {
  darkBackground?: boolean;
}

export const B = A.extend`
  background-color: ${(props: Bprops) =>
    props.darkBackground ? 'grey' : 'white'};
`;

function test() {
  return (
    <React.Fragment>
      <A icon="str1" />
      <B icon="str2" darkBackground />
    </React.Fragment>
  );
}

有没有办法用在此级别上指定的Bprops 属性重写行export const B = A.extend,就像我们在这里:export const A = styled&lt;Aprops, 'div'&gt;('div')

就像export const B = styled&lt;Bprops &amp; Aprops&gt;(A),所以我不需要在组件B 的声明中需要的任何地方复制此代码(props: Bprops)

【问题讨论】:

    标签: reactjs typescript typescript2.0 styled-components


    【解决方案1】:

    似乎我找到了解决方案:

    export const B = styled<Aprops & Bprops>(A)`
      background-color: ${props =>
        props.darkBackground ? 'grey' : 'white'};
    `;
    

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 2019-03-28
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 2017-10-19
      • 2021-06-02
      • 1970-01-01
      • 2020-06-12
      相关资源
      最近更新 更多