【问题标题】:Css Properties and TextStyle TypesCss 属性和 TextStyle 类型
【发布时间】:2025-12-23 19:40:16
【问题描述】:

我有一个 textStyle,它是 TextStyle 的一种(它来自 react-native 类型)或 React.CSSProperties。我想将此类型传递给 html span 元素的样式属性。 style 属性接受 React.CSSProperties 的类型。我的界面和跨度元素是:

export interface IBaseTextStyleType {
    textStyle:  React.CSSProperties | TextStyle
}

<span style={style.textStyle}>
    {this.props.children || this.props.text}
</span>

我在 span 样式中遇到了这个错误:

Type 'CSSProperties | TextStyle' is not assignable to type 'CSSProperties'.
  Type 'TextStyle' is not assignable to type 'CSSProperties'.
    Types of property 'aspectRatio' are incompatible.
      Type 'number' is not assignable to type 'AspectRatio'.

我怎样才能摆脱这个错误?

【问题讨论】:

  • TextStyle 在 React Native 的 Text 组件上有意义,而不是在采用 CSSProperties 类型的 span 上。这里的目标是什么?
  • 我的目标是:收集双方的公共区域(网络和本地)。 Web 具有特定的样式道具,而 rn 也具有特定的样式道具。但是有共同的风格。开发者可以选择 React.CSSProperties 或 TextStyle。
  • 我认为更好的设计是创建一个类似 (props: IBaseTextStyleType) =&gt; isWeb ? &lt;span style={props.textStyle as CSSProperties}&gt;{...}&lt;/span&gt; : &lt;Text style={props.textStyle as TextStyle}&gt;{...}&lt;/Text&gt; 的组件
  • 那就太好了,但是。我刚刚为两者创建了所有组件。
  • 据我所知 &lt;span&gt; 在 react native 项目中是行不通的,不是吗?

标签: typescript react-native


【解决方案1】:

您尝试像这样定义style.textStyle 的类型:

<span style={style.textStyle as React.CSSProperties}>
    {this.props.children || this.props.text}
</span>

【讨论】:

    最近更新 更多