自定义组件
如果你想创建类似于 Box
或 Text
的自定义组件,并自行决定使用哪些预定义的 Restyle 函数,请使用 createRestyleComponent
辅助函数。
import {
createRestyleComponent,
createVariant,
spacing,
SpacingProps,
VariantProps,
} from '@shopify/restyle';
import {Theme} from './theme';
type Props = SpacingProps<Theme> & VariantProps<Theme, 'cardVariants'>;
const Card = createRestyleComponent<Props, Theme>([
spacing,
createVariant({themeKey: 'cardVariants'}),
]);
export default Card;
对于更高级的组件,你可能希望使用 useRestyle
Hook。
import {TouchableOpacity, View} from 'react-native';
import {
useRestyle,
spacing,
border,
backgroundColor,
SpacingProps,
BorderProps,
BackgroundColorProps,
composeRestyleFunctions,
} from '@shopify/restyle';
import Text from './Text';
import {Theme} from './theme';
type RestyleProps = SpacingProps<Theme> &
BorderProps<Theme> &
BackgroundColorProps<Theme>;
const restyleFunctions = composeRestyleFunctions<Theme, RestyleProps>([
spacing,
border,
backgroundColor,
]);
type Props = RestyleProps & {
onPress: () => void;
label: string;
};
const Button = ({onPress, label, ...rest}: Props) => {
const props = useRestyle(restyleFunctions, rest);
return (
<TouchableOpacity onPress={onPress}>
<View {...props}>
<Text variant="buttonLabel">{label}</Text>
</View>
</TouchableOpacity>
);
};