如何使用 @shopify/restyle 在 React Native 中构建类型强制的 UI 组件
自从我在博客上写一篇技术文章以来已经有一段时间了,这是一篇关于使用 @shopify/restyle 和 expo 在 React Native 中构建类型强制 UI 组件的新文章。
@shopify/restyle 是一个强大的 React Native 样式库,可为您的 UI 组件带来类型安全性和一致性。与传统的样式方法不同,Restyle 允许您创建集中式主题配置,在整个应用程序中强制执行设计系统原则。
入门
项目设置
- 使用 expo 设置您的 React Native 项目
npx create-expo-app@latest
- 转到您的项目目录并使用 expo 安装 @shopify/restyle 包
cd /path/to/project npx expo install @shopify/restyle
创建你的主题
创建 theme.tsx 文件来定义您的设计系统:
touch theme.tsx
- 复制并粘贴默认主题配置
import {createTheme} from '@shopify/restyle'; const palette = { purpleLight: '#8C6FF7', purplePrimary: '#5A31F4', purpleDark: '#3F22AB', greenLight: '#56DCBA', greenPrimary: '#0ECD9D', greenDark: '#0A906E', black: '#0B0B0B', white: '#F0F2F3', }; const theme = createTheme({ colors: { mainBackground: palette.white, cardPrimaryBackground: palette.purplePrimary, }, spacing: { s: 8, m: 16, l: 24, xl: 40, }, textVariants: { header: { fontWeight: 'bold', fontSize: 34, }, body: { fontSize: 16, lineHeight: 24, }, defaults: { // We can define a default text variant here. }, }, }); export type Theme = typeof theme; export default theme;
实施主题提供者
更新您的 app/_layout.tsx:
import { DarkTheme, DefaultTheme } from "@react-navigation/native"; import { useFonts } from "expo-font"; import { Stack } from "expo-router"; import * as SplashScreen from "expo-splash-screen"; import { StatusBar } from "expo-status-bar"; import { useEffect } from "react"; import "react-native-reanimated"; import { ThemeProvider } from "@shopify/restyle"; import theme from "@/theme"; // Prevent the splash screen from auto-hiding before asset loading is complete. SplashScreen.preventAutoHideAsync(); export default function RootLayout() { const [loaded] = useFonts({ SpaceMono: require("../assets/fonts/SpaceMono-Regular.ttf"), }); useEffect(() => { if (loaded) { SplashScreen.hideAsync(); } }, [loaded]); if (!loaded) { return null; } return ( <ThemeProvider theme={theme}> <Stack> <Stack.Screen name="(tabs)" options={{ headerShown: false }} /> <Stack.Screen name="+not-found" /> </Stack> <StatusBar> <h2> Creating Reusable Components </h2> <h3> Text Component </h3> <pre class="brush:php;toolbar:false">touch components/Text.tsx
// In components/Text.tsx import {createText} from '@shopify/restyle'; import {Theme} from '../theme'; export const Text = createText<Theme>();
让我们在主屏幕上使用它
import { Text } from "@/components/Text"; import { SafeAreaView } from "react-native-safe-area-context"; export default function HomeScreen() { return ( <SafeAreaView> <Text margin="m" variant="header"> This is the Home screen. Built using @shopify/restyle. </Text> </SafeAreaView> ); }
正如您在上面的代码中看到的,我们将边距作为“m”而不是数字传递。我们从 theme.tsxfile 中获取值。
// ./theme.tsx const theme = createTheme({ spacing: { s: 8, m: 16, // margin="m" l: 24, xl: 40, }, textVariants: { header: { // our text header variant fontWeight: 'bold', fontSize: 34, }, body: { fontSize: 16, lineHeight: 24, }, }, // ...rest of code }, });
这就是我们的主页视图的外观
骨架装载机组件
让我们构建一张骨架装载机卡
touch components/SkeletonLoader.tsx
// components/SkeletonLoader.tsx import { BackgroundColorProps, createBox, createRestyleComponent, createVariant, spacing, SpacingProps, VariantProps, } from "@shopify/restyle"; import { Theme } from "@/theme"; import { View } from "react-native"; const Box = createBox<Theme>(); type Props = SpacingProps<Theme> & VariantProps<Theme, "cardVariants"> & BackgroundColorProps<Theme> & React.ComponentProps<typeof View>; const CardSkeleton = createRestyleComponent<Props, Theme>([ spacing, createVariant({ themeKey: "cardVariants" }), ]); const SkeletonLoader = () => { return ( <CardSkeleton variant="elevated"> <Box backgroundColor="cardPrimaryBackground" height={20} marginBottom="s" width="70%" overflow="hidden" borderRadius={"m"} > </Box> <Box backgroundColor="cardPrimaryBackground" height={100} marginBottom="s" width="90%" overflow="hidden" borderRadius={"m"} > </Box> <Box backgroundColor="cardPrimaryBackground" height={50} marginBottom="s" width="70%" overflow="hidden" borderRadius={"m"} > </Box> </CardSkeleton> ); }; export default SkeletonLoader;
- 我们从 @shopify/restyle 包中创建一个新框作为预定义组件,这将是我们创建骨架框的方式
const Box = createBox<Theme>();
- 使用createStyleComponent创建一个新的CardSkeleton组件来创建自定义组件,我们传递了必须在theme.tsx文件中定义的间距和cardVariants的道具
type Props = SpacingProps<Theme> & VariantProps<Theme, "cardVariants"> & BackgroundColorProps<Theme> & React.ComponentProps<typeof View>; const CardSkeleton = createRestyleComponent<Props, Theme>([ spacing, createVariant({ themeKey: "cardVariants" }), ]);
- 创建一个 SkeletonLoader 组件来渲染我们的 Skelton Card 组件
// components/SkeletonLoader.tsx export const SkeletonLoader = () => { return ( <CardSkeleton variant="elevated"> <Box backgroundColor="cardPrimaryBackground" height={20} marginBottom="s" width="70%" overflow="hidden" borderRadius={"m"} ></Box> <Box backgroundColor="cardPrimaryBackground" height={100} marginBottom="s" width="90%" overflow="hidden" borderRadius={"m"} ></Box> <Box backgroundColor="cardPrimaryBackground" height={50} marginBottom="s" width="70%" overflow="hidden" borderRadius={"m"} ></Box> </CardSkeleton> ); };
我们还剩下一件事要使其正常工作,更新 theme.tsx 文件以拥有 cardVariants
const theme = createTheme({ colors: { // Add Black Color to use it later on black: palette.black, }, // Add Border Radius Variants borderRadii: { s: 4, m: 10, l: 25, xl: 75, }, // Add Card Variants cardVariants: { elevated: { shadowColor: "black", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, borderRadius: "m", }, defaults: { padding: "m", borderRadius: "m", }, }, });
太棒了,但是让我们为我们的组件添加动画
// components/SkeletonLoader.tsx const ShimmerAnimation = () => { const shimmerTranslate = useRef(new Animated.Value(0)).current; useEffect(() => { Animated.loop( Animated.timing(shimmerTranslate, { toValue: 1, duration: 1500, useNativeDriver: true, }) ).start(); }, [shimmerTranslate]); const translateX = shimmerTranslate.interpolate({ inputRange: [0, 1], outputRange: [-300, 300], }); return ( <Animated.View > <p>and let’s use it in our Skeleton Loader Component<br> </p> <pre class="brush:php;toolbar:false">// components/SkeletonLoader.tsx export const SkeletonLoader = () => { return ( <CardSkeleton variant="elevated"> <Box backgroundColor="cardPrimaryBackground" height={20} marginBottom="s" width="70%" overflow="hidden" borderRadius={"m"} > <ShimmerAnimation /> </Box> <Box backgroundColor="cardPrimaryBackground" height={100} marginBottom="s" width="90%" overflow="hidden" borderRadius={"m"} > <ShimmerAnimation /> </Box> <Box backgroundColor="cardPrimaryBackground" height={50} marginBottom="s" width="70%" overflow="hidden" borderRadius={"m"} > <ShimmerAnimation /> </Box> </CardSkeleton> ); };
这是完整的组件代码:
// components/SkeletonLoader.tsx import { useEffect, useRef } from "react"; import { Animated } from "react-native"; import { BackgroundColorProps, createBox, createRestyleComponent, createVariant, spacing, SpacingProps, VariantProps, } from "@shopify/restyle"; import { Theme } from "@/theme"; import { View } from "react-native"; const Box = createBox<Theme>(); const ShimmerAnimation = () => { const shimmerTranslate = useRef(new Animated.Value(0)).current; useEffect(() => { Animated.loop( Animated.timing(shimmerTranslate, { toValue: 1, duration: 1500, useNativeDriver: true, }) ).start(); }, [shimmerTranslate]); const translateX = shimmerTranslate.interpolate({ inputRange: [0, 1], outputRange: [-300, 300], }); return (Et voila, we made a skeleton loader card using @shopify/restyle using
Support for dark mode
Let’s start with adding dark theme configuration, in your theme.tsxfile
// theme.tsx export const darkTheme: Theme = { ...theme, colors: { ...theme.colors, mainBackground: palette.white, cardPrimaryBackground: palette.purpleDark, greenPrimary: palette.purpleLight, }, textVariants: { ...theme.textVariants, defaults: { ...theme.textVariants.header, color: palette.purpleDark, }, },登录后复制
通过将深色主题配置添加到我们的layout.tsx 文件中来将其添加到应用程序布局中
npx create-expo-app@latest
- 基于颜色模式,使用默认的浅色主题或在深色模式下使用 theme.tsx 文件中定义的 darkTheme 配置
// app/_layout.tsx 从“@/theme”导入主题,{ darkTheme }; //...其余代码 <ThemeProvider主题={colorSchema ===“深色”?黑暗主题:主题}> <堆栈> <Stack.Screen name="(tabs)" options={{ headerShown: false }} /> > <Stack.Screen name="未找到" /> </堆栈> <p>这是深色和浅色模式。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173310152340178.jpg" class="lazy" alt="How to build type-enforced UI components in React Native using @shopify/restyle"></p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173310152557660.jpg" class="lazy" alt="How to build type-enforced UI components in React Native using @shopify/restyle"></p> <p>瞧,我们成功地使用 @shopify/restyle 包创建了类型强制的 UI 组件</p> <p>谢谢你:)</p>
以上是如何使用 @shopify/restyle 在 React Native 中构建类型强制的 UI 组件的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。
