搜尋
首頁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
C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:學習曲線和易用性Python vs. JavaScript:學習曲線和易用性Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.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 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)