搜索
首页web前端js教程如何使用 @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>
        <stack.screen name="+not-found"></stack.screen>
      </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>();

</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
  },
});

这就是我们的主页视图的外观

How to build type-enforced UI components in React Native using @shopify/restyle

骨架装载机组件

让我们构建一张骨架装载机卡

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> &
  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;

</props></typeof></theme></theme></theme></theme>
  • 我们从 @shopify/restyle 包中创建一个新框作为预定义组件,这将是我们创建骨架框的方式
const Box = createBox<theme>();
</theme>
  • 使用createStyleComponent创建一个新的CardSkeleton组件来创建自定义组件,我们传递了必须在theme.tsx文件中定义的间距和cardVariants的道具
type Props = SpacingProps<theme> &
  VariantProps<theme> &
  BackgroundColorProps<theme> &
  React.ComponentProps<typeof view>;

const CardSkeleton = createRestyleComponent<props theme>([
  spacing,
  createVariant({ themeKey: "cardVariants" }),
]);
</props></typeof></theme></theme></theme>
  • 创建一个 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></shimmeranimation>
      </box>

      <box backgroundcolor="cardPrimaryBackground" height="{100}" marginbottom="s" width="90%" overflow="hidden" borderradius='{"m"}'>
        <shimmeranimation></shimmeranimation>
      </box>
      <box backgroundcolor="cardPrimaryBackground" height="{50}" marginbottom="s" width="70%" overflow="hidden" borderradius='{"m"}'>
        <shimmeranimation></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 (
    <animated.view>



<p>Et voila, we made a skeleton loader card using @shopify/restyle using </p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173310152233378.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="How to build type-enforced UI components in React Native using @shopify/restyle"></p>

<h2>
  
  
  Support for dark mode
</h2>

<p>Let’s start with adding dark theme configuration, in your theme.tsxfile<br>
</p>

<pre class="brush:php;toolbar:false">// 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>
      
        <stack.screen name="(tabs)" options="{{" headershown: false></stack.screen> >
        <stack.screen name="未找到"></stack.screen>
      堆栈>
      



<p>这是深色和浅色模式。</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173310152340178.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="How to build type-enforced UI components in React Native using @shopify/restyle"></p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173310152557660.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="How to build type-enforced UI components in React Native using @shopify/restyle"></p>

<p>瞧,我们成功地使用 @shopify/restyle 包创建了类型强制的 UI 组件</p>

<p>谢谢你:)</p>


          

            
        </themeprovider>

以上是如何使用 @shopify/restyle 在 React Native 中构建类型强制的 UI 组件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript数据类型:浏览器和nodejs之间是否有区别?JavaScript数据类型:浏览器和nodejs之间是否有区别?May 14, 2025 am 12:15 AM

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScript评论:使用//和 / * * / * / * /JavaScript评论:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

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

热门文章

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具