【问题标题】:font-size type of an argument of a Styled-ComponentStyled-Component 参数的字体大小类型
【发布时间】:2021-08-12 19:46:25
【问题描述】:

如何在Styled-Component 中指定传递的参数是font-size 类型?

这是我在 TypeScript 中的代码:

export const StyledOldPrice = styled.span<{ fontSize: <HERE> }>`
  font-weight: 400;
  font-size: ${({ fontSize }) => (fontSize ? fontSize : "smaller")};
  align-self: flex-end;
  margin-bottom: 5%;
  color: #656b6f;
`;

在使用样式时获取 IntelliSense,例如larger、x-small、smaller ...等

<StyledOldPrice fontSize={...} />

【问题讨论】:

    标签: css typescript types styled-components


    【解决方案1】:

    您可以使用“string literal types”

    export const StyledOldPrice = styled.span<{
      fontSize: "smaller" | "larger" | "x-small";
    }>`
    

    更新

    为了使fontSize类型与html元素fontSize相同,有2个选项:

    1. 从csstype导入(这是jsx使用的)
    import type {StandardLonghandProperties} from 'csstype';
    
    export const StyledOldPrice = styled.span<{
      fontSize: StandardLonghandProperties["fontSize"];
    }>`
    

    +:它将接受“常规”fontSize 接受的任何值(例如 '20px'、20、'smaller' 等)

    -: 不会有自动完成,因为fontSize 基本上可以是任何string 或number。

    注意:理想情况下,我们可以只从联合中取出字符串文字并删除string,类似于Exclude&lt;StandardLonghandProperties["fontSize"], string&gt;,但不幸的是,目前是it's not possible。


    1. 从csstype 复制fontSize 和AbsoluteSize,不带string 和number。
    import type { Globals } from 'csstype';
    type AbsoluteSize = "large" | "medium" | "small" | "x-large" | "x-small" | "xx-large" | "xx-small" | "xxx-large";
    type FontSize = Globals | AbsoluteSize | "larger" | "smaller";
    
    export const StyledOldPrice = styled.span<{
      fontSize: FontSize;
    }>`
    

    +:会有自动补全。

    -: 它将只接受“预定义”值,例如smaller、inherit 等。

    https://codesandbox.io/s/interesting-violet-1qdmp?file=/src/App.tsx

    【讨论】:

    • 没有其他方法可以检测和获取所有定义的值?
    • 首先,据我测试,即使我在常规 div 上键入 style 也不会自动完成。我认为是因为fontSize 也可以是字符串或数字,因此您基本上可以将其设置为任何值。但是如果你想让它和每个元素的fontSize 一样,你可以使用StandardLonghandProperties["fontSize"] by import type {StandardLonghandProperties} from 'csstype'; 类型。您仍然不会获得自动完成功能。如果你想通过限制关闭列表中的选项来自动完成(如smaller、larger、inherit 等),你可以import type {Globals, AbsoluteSize} from 'csstype';
    • 还有type FontSize = Globals | AbsoluteSize | "larger" | "smaller"。我已经更新了代码框。
    • 我已经更新了答案。谢谢提醒。
    • 你是对的 :( 好像你也必须复制AbsoluteSize。
    【解决方案2】:

    或者甚至更好更简单的方法,接受CSS 中的所有值font-size 属性接受包括字符串“px, em, ...etc”:

    import styled from "styled-components";
    export type FontSize = Property.FontSize;
    
    export const StyledOldPrice = styled.span<{
      fontSize: FontSize;
    }>`
    

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2020-05-17
      • 2020-03-09
      • 2020-01-06
      • 2018-04-16
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多