【发布时间】: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 && (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