【问题标题】:What is the correct syntax for BoxSizing in a React CSS ObjectReact CSS对象中BoxSizing的正确语法是什么
【发布时间】:2021-12-26 17:46:29
【问题描述】:

我正在尝试为 React 中的道具赋予样式,但我不知道正确的编写方式:

<PhoneInput
   inputStyle={!(window.innerWidth <= 768) ? {...InputDivStyle, ...PhoneInputStyle, textIndent: "96px"} : {...InputDivStyle, ...PhoneInputStyle, textIndent: "32px"}}
</PhoneInput>

inputStyle 给了我错误:

Types of property 'boxSizing' are incompatible. Type 'string' is not assignable to type 'BoxSizing | undefined'.ts(2322)

export const PhoneInputStyle = {
  fontSize: "clamp(13px, 1.111vw, 16px)",
  lineHeight: "clamp(15px, 1.319vw, 19px)",
  position: "relative",
  width: "100%",
  height: "51px",
  cursor: "pointer",
  display: "flex",
  flexDirection: "row",
  alignItems: "center",
  padding: "8px 16px",
  border: `1px solid black`,
  boxSizing: `border-box`, //This ain't right, I tried "border-box" and it didn't work either
  borderRadius: "10px",
  outline: "none",
  gridRowStart: "1",
  gridColumnStart: "1",
}

我很确定这只是语法错误,但我找不到正确的 boxSizing 方法。

【问题讨论】:

  • 这是我的问题,我不知道怎么写,因为写boxSizing: border-boxboxSizing: borderBox给了我Cannot find name 'border-box'
  • @Terry,BoxSizing 不是枚举。问题是关于一般字符串与特定字符串

标签: javascript html css reactjs typescript


【解决方案1】:

我遇到了同样的问题,我也明确地解决了它,给 PhoneInputStyle 一个 CSSProperties 类型。成功了,谢谢!

【讨论】:

    【解决方案2】:
    export const PhoneInputStyle = {
      // ...
      boxSizing: `border-box`,
      // ...
    }
    

    由于你没有在这个对象上明确的类型,打字稿会自动创建一个类型。它看到 boxSizing 是一个字符串,所以它给 boxSizing 类型string。不幸的是,这对于你最终要做的事情来说太宽泛了。 box sizing 不能是任何字符串,而只能是非常具体的字符串。

    我建议你给这个对象一个明确的CSSProperties类型。除其他外,此类型会将 boxSizing 限制为其合法值:

    import { CSSProperties } from "react";
    
    export const PhoneInputStyle: CSSProperties = {
      // ...
      boxSizing: `border-box`,
      // ...
    }
    

    【讨论】:

    • 非常感谢,这个问题我遇到过几次了,一直没找到答案。
    猜你喜欢
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2010-10-03
    • 2021-10-09
    • 2017-10-18
    • 2014-04-19
    相关资源
    最近更新 更多