【问题标题】:How to type the style property for components to accept arrays?如何键入组件的样式属性以接受数组?
【发布时间】:2019-07-05 05:31:43
【问题描述】:

在 React Native 中,视图元素接受 style 属性,该属性在驼峰式对象中使用 CSS 属性名称:

const styleObj = {
  width: 200,
  marginTop: 10
}

元素也接受这样的样式对象数组:

<MyComponent style={[ styleObj, styleProp && styleProp ]} />

我有几个依赖于共享基本按钮界面的抽象按钮组件。为简单起见:

interface IButton {
  style?: ViewStyle | ViewStyle[] // <-- ViewStyle is exported by react native, and contains all the allowed style properties for a View component
}

我认为这个定义已经足够了,但我遇到了一些我难以理解的问题。

我有一个DropDown 组件,它呈现一个Button。当我使用 style 道具时出现错误:

<Button
  style={[
    {
      backgroundColor: backgroundColor || COLORS.lightRed,
      borderRadius: 3,
      height: 44,
      width: '100%',
     },
     style && style, // <-- type is ViewStyle | ViewStyle[], this is passed in as a prop
  ]}

上面抛出错误:

Type (ViewStyle | ViewStyle[] | undefined)[] is not assignable to ViewStyle | ViewStyle[] | undefined

如果我投射风格:style &amp;&amp; (style as ViewStyle) 我会得到一个不同的错误:

Type (ViewStyle | undefined)[] is not assignable to ViewStyle[]

如果我将整个数组转换为ViewStyle,则错误会清除:

<Button
  style={[
    {
      backgroundColor: backgroundColor || COLORS.lightRed,
      borderRadius: 3,
      height: 44,
      width: '100%',
     },
     style && style,
  ] as ViewStyle}

这很好,但我有点困惑。我有一种预感,因为我的组件使用相同的 props 接口,TypeScript 会变得混乱。最终我不确定为什么会发生这些错误,以及我需要依赖强制转换的定义有什么不正确的地方。

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    这应该是显而易见的,但我花了一段时间才找到最佳解决方案。

    输入样式道具时,请使用ViewStyleTextStyle 等(而不是StyleProp&lt;T&gt;),并且在传递样式数组时只需使用Stylesheet.flatten() 以消除任何类型的不兼容性:

    <Button
      style={Stylesheet.flatten([
        {
          backgroundColor: backgroundColor || COLORS.lightRed,
          borderRadius: 3,
          height: 44,
          width: '100%',
         },
         style && style,
      ])}
    

    【讨论】:

    • 注意使用StyleSheet.flatten() 会移除 react-native StyleSheet 优化
    猜你喜欢
    • 2019-10-13
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2022-01-10
    • 2017-10-05
    • 2016-11-30
    • 2012-10-25
    相关资源
    最近更新 更多