响应式值
Restyle 支持的任何 prop 都可以选择性地接受每个屏幕尺寸的值,屏幕尺寸由主题中的 breakpoints
对象定义
// In your theme
const theme = createTheme({
// ...
breakpoints: {
phone: 0,
tablet: 768,
}
})
// Props always accept either plain values
<Box flexDirection="row" />
// Or breakpoint-specific values
<Box flexDirection={{phone: 'column', tablet: 'row'}} />
如果您需要在自定义组件中提取响应式 prop 的值(例如在组件样式之外使用它),您可以使用 useResponsiveProp
hook
import {
ColorProps,
createBox,
useResponsiveProp,
useTheme,
} from '@shopify/restyle';
import React from 'react';
import {
ActivityIndicator,
TouchableOpacity,
TouchableOpacityProps,
} from 'react-native';
import Text from './Text';
import {Theme} from './theme';
const BaseButton = createBox<Theme, TouchableOpacityProps>(TouchableOpacity);
type Props = React.ComponentProps<typeof BaseButton> &
ColorProps<Theme> & {
label: string;
isLoading?: boolean;
};
const Button = ({
label,
isLoading,
color = {phone: 'purple', tablet: 'blue'},
...props
}: Props) => {
const theme = useTheme<Theme>();
// Will be 'purple' on phone and 'blue' on tablet
const textColorProp = useResponsiveProp(color);
// Can safely perform logic with the extracted value
const bgColor = textColorProp === 'purple' ? 'lightPurple' : 'lightBlue';
return (
<BaseButton
flexDirection="row"
columnGap="s"
backgroundColor={bgColor}
{...props}
>
<Text variant="buttonLabel" color={color}>
{label}
</Text>
{isLoading ? (
<ActivityIndicator color={theme.colors[textColorProp]} />
) : null}
</BaseButton>
);
};