블로그에 기술 게시물을 쓴 지 꽤 오랜 시간이 흘렀습니다. @shopify/restyle 및 expo를 사용하여 React Native에서 유형 적용 UI 구성 요소를 구축하는 방법에 대한 새로운 게시물이 있습니다.
@shopify/restyle은 UI 구성 요소에 유형 안전성과 일관성을 제공하는 강력한 React Native용 스타일 라이브러리입니다. 기존 스타일링 접근 방식과 달리 Restyle을 사용하면 전체 애플리케이션에 걸쳐 디자인 시스템 원칙을 적용하는 중앙 집중식 테마 구성을 만들 수 있습니다.
시작하기
프로젝트 설정
- expo를 사용하여 반응 네이티브 프로젝트 설정
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 }, });
홈페이지 보기는 다음과 같습니다
스켈레톤 로더 구성요소
스켈레톤 로더 카드를 만들어 봅시다
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 패키지에서 사전 정의된 구성 요소로 새 상자를 생성하며 이것이 Skeleton Box를 생성하는 방법입니다.
const Box = createBox<theme>(); </theme>
- createStyleComponent를 사용하여 새 CardSkeleton 구성 요소를 생성하여 사용자 정의 구성 요소를 생성하고 theme.tsx 파일에서 정의해야 하는 간격 및 카드 변수인 소품을 전달했습니다.
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>
- Skelton Card 구성 요소를 렌더링하기 위한 SkeletonLoader 구성 요소 생성
// 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.tsxfile을 업데이트하여 카드 변형을 갖도록 해야 합니다.
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 theme="{colorSchema" darktheme :> <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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript는 웹 페이지의 상호 작용과 역학을 향상시키기 때문에 현대 웹 사이트의 핵심입니다. 1) 페이지를 새로 고치지 않고 콘텐츠를 변경할 수 있습니다. 2) Domapi를 통해 웹 페이지 조작, 3) 애니메이션 및 드래그 앤 드롭과 같은 복잡한 대화식 효과를 지원합니다. 4) 성능 및 모범 사례를 최적화하여 사용자 경험을 향상시킵니다.

C 및 JavaScript는 WebAssembly를 통한 상호 운용성을 달성합니다. 1) C 코드는 WebAssembly 모듈로 컴파일되어 컴퓨팅 전력을 향상시키기 위해 JavaScript 환경에 도입됩니다. 2) 게임 개발에서 C는 물리 엔진 및 그래픽 렌더링을 처리하며 JavaScript는 게임 로직 및 사용자 인터페이스를 담당합니다.

JavaScript는 웹 사이트, 모바일 응용 프로그램, 데스크탑 응용 프로그램 및 서버 측 프로그래밍에서 널리 사용됩니다. 1) 웹 사이트 개발에서 JavaScript는 HTML 및 CSS와 함께 DOM을 운영하여 동적 효과를 달성하고 jQuery 및 React와 같은 프레임 워크를 지원합니다. 2) 반응 및 이온 성을 통해 JavaScript는 크로스 플랫폼 모바일 애플리케이션을 개발하는 데 사용됩니다. 3) 전자 프레임 워크를 사용하면 JavaScript가 데스크탑 애플리케이션을 구축 할 수 있습니다. 4) node.js는 JavaScript가 서버 측에서 실행되도록하고 동시 요청이 높은 높은 요청을 지원합니다.

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
