跳至主要内容

样式函数

样式函数是 Restyle 的核心。它们指定了属性如何映射到最终样式对象中的值,然后可以将该样式对象传递给 React Native 组件。这些属性支持响应式值,并且可以映射到主题中的值。

预定义的样式函数

Restyle 库为了方便起见,提供了一些预定义的样式函数。括号内的属性是前面属性名称的别名/简写。

样式函数属性主题键
backgroundColorbackgroundColor[bg]colors
colorcolorcolors
opacityopacitynone
visibledisplay (将 true / false 映射到 flex / none)none
spacingmargin[m], marginTop[mt], marginRight[mr], marginBottom[mb], marginLeft[ml], marginStart[ms], marginEnd[me], marginHorizontal[mx], marginVertical[my], padding[p], paddingTop[pt], paddingRight[pr], paddingBottom[pb], paddingLeft[pl], paddingStart[ps], paddingEnd[pe], paddingHorizontal[px], paddingVertical[py], gap[g], rowGap[rG], columnGap[cG]spacing
layoutwidth, height, minWidth, maxWidth, minHeight, maxHeight, overflow, aspectRatio, alignContent, alignItems, alignSelf, justifyContent, flex, flexBasis, flexDirection, flexGrow, flexShrink, flexWrapnone
positionposition, top, right, bottom, left, start, endnone
positionzIndexzIndices
borderborderBottomWidth, borderLeftWidth, borderRightWidth, borderStartWidth, borderEndWidth, borderStyle, borderTopWidth, borderWidthnone
borderborderColor, borderTopColor, borderRightColor, borderLeftColor, borderStartColor, borderEndColor, borderBottomColorcolors
borderborderRadius, borderBottomLeftRadius, borderBottomRightRadius, borderBottomStartRadius, borderBottomEndRadius, borderTopLeftRadius, borderTopRightRadius, borderTopStartRadius, borderTopEndRadiusborderRadii
shadowshadowOpacity, shadowOffset, shadowRadius, elevationnone
shadowshadowColorcolors
textShadowtextShadowOffset, textShadowRadiusnone
textShadowtextShadowColorcolors
typographyfontFamily, fontSize, fontStyle, fontWeight, includeFontPadding, fontVariant, letterSpacing, lineHeight, textAlign, textAlignVertical, textDecorationColor, textDecorationLine, textDecorationStyle, textTransform, verticalAlign, writingDirectionnone

自定义样式函数

要定义你自己的样式函数,请使用 createRestyleFunction 辅助函数

import {createRestyleFunction, createRestyleComponent} from '@shopify/restyle'
const transparency = createRestyleFunction({
property: 'transparency',
styleProperty: 'opacity',
transform: ({value}: {value: number}) => 1 - value,
});

const TransparentComponent = createRestyleComponent([transparency])

<TransparentComponent transparency={0.5} />

参数

  • property:组件属性的名称,该函数将接收该属性的值。
  • styleProperty:要映射到的样式对象中的属性的名称。默认为 property 的值。
  • transform({value, theme, themeKey}):一个可选函数,它将属性的值转换为将插入到样式对象中的值。
  • themeKey:主题中的一个可选键,用于映射值,例如 colors