变体
变体是一种 Restyle 函数的形式,它将一个 prop 映射到多个其他 prop,以便与 Restyle 函数一起使用。变体始终需要映射到主题中的一个键。
// In theme
const theme = createTheme({
// ...
spacing: {
s: 8,
m: 16,
l: 24,
},
colors: {
cardPrimaryBackground: '#EEEEEE',
},
breakpoints: {
phone: 0,
tablet: 768,
},
cardVariants: {
defaults: {
// We can define defaults for the variant here.
// This will be applied after the defaults passed to createVariant and before the variant defined below.
},
regular: {
// We can refer to other values in the theme here, and use responsive props
padding: {
phone: 's',
tablet: 'm',
},
},
elevated: {
padding: {
phone: 's',
tablet: 'm',
},
shadowColor: '#000',
shadowOpacity: 0.2,
shadowOffset: {width: 0, height: 5},
shadowRadius: 15,
elevation: 5,
}
}
})
import {createVariant, createRestyleComponent, VariantProps} from '@shopify/restyle'
import {Theme} from './theme';
const variant = createVariant<Theme, 'cardVariants'>({
themeKey: 'cardVariants',
defaults: {
margin: {
phone: 's',
tablet: 'm',
},
backgroundColor: 'cardPrimaryBackground',
},
})
const Card = createRestyleComponent<
VariantProps<Theme, 'cardVariants'> & BoxProps<Theme>,
Theme,
>([variant], Box)
<Card variant="elevated" />
// createVariant and createRestyleComponent are often combined into a single
// call, which improves the type hinting as well:
const Card = createRestyleComponent<
VariantProps<Theme, 'cardVariants'> & React.ComponentProps<typeof Box>,
Theme
>(
[
createVariant({
themeKey: 'cardVariants',
defaults: {
margin: {
phone: 's',
tablet: 'm',
},
backgroundColor: 'cardPrimaryBackground',
},
}),
],
Box,
);
参数
property
:将映射到变体的组件 prop 的名称。默认为variant
。themeKey
:主题中用于映射值的键。与createRestyleFunction
不同,创建变体时此选项是必需的。defaults
:在应用主题中的任何值之前要应用的默认值。