搜尋
首頁web前端js教程我如何為我的 React Native 專案設定設計系統以加快開發速度

Ever built apps that you wouldn't want to use yourself?

When I was a junior app developer, I used to build chaotic user interfaces.

Sometimes when looking at those UIs, I used to think "who in the world would even want to use this? It looks awful".

Other times, there was just "something off" that I just couldn't point out.

While I used to get amazing polished designs from design team, my apps would not look even 20% as good.

I was aware of this problem, and to fix it I went down on a rabbit hole of research in which I came across concept of having a design system which transformed the way I build apps.

What is this amazing thing called Design System?

It's crucial to understand what a design system is to be able to understand why do we need it.

Design system is basically a centralized source of truth for yours and your teams design decisions. It tells you what colours to use and where? How many types of buttons the app will have? Will the cards in your list have shadows? All answers comes from a design system.

Here are some of the benefits of having a design system:

  • Consistent UIs: Your interface will not have those weird gaps here and there for no reason. It will look and feel uniform across all devices.

  • Rapid decisions: Design systems enforces a certain set of constraints to make your decisions easier, not harder. The more options you have, the more analysis-paralysis you encounter.

  • Scalable Apps: As the app grows, a design system helps in reusing components rather than building from scratch.

  • Focus on development: You no longer have to stress whether the button should be green or blue. Instead, you'll focus on what matters.

Tools & Libraries

While there are tons of React Native UI libraries out there, I use custom approach as I've had horrible experiences with most of them regarding performance and bugs.

The only library I rely on for my approach is react-native-size-matters.

Now before you scream "size doesn't matter!", let me assure you it does. Especially, when it comes to mobile apps.

You don't want your users opening your app, seeing a giant logo covering everything, and think "What in the ugly..." before they delete without even trying because your logo hid the button.

That's where react-native-size-matters helps. It makes your apps responsive by scaling your components to fit the device. So, no matter which device users have, your logo stays exactly where you put it.

Set up theme

One of the first thing I define is my core design tokens. These are the building blocks of my design system. These include color palettes, typography, spacings, and font sizes.

I do this by creating a theme.ts file with the following code:


import {moderateScale} from 'react-native-size-matters';

// after installing custom fonts:
export const FontFamily = {
  bold: 'Poppins-Bold',
  semibold: 'Poppins-SemiBold',
  medium: 'Poppins-Medium',
  regular: 'Poppins-Regular',
  thin: 'Poppins-Thin',
};

const colors = {
  primary100: '#2E2C5F',
  primary80: '#524DA0',
  primary60: '#736DDF',
  primary40: '#A09BFF',
  primary20: '#DCDAFF',

  secondary100: '#484A22',
  secondary80: '#858945',
  secondary60: '#D9DF6D',
  secondary40: '#F8FCA1',
  secondary20: '#FDFFD4',

  neutral100: '#131218',
  neutral90: '#1D1C25',
  neutral80: '#272631',
  neutral70: '#343341',
  neutral60: '#3E3D4D',
  neutral50: '#53526A',
  neutral40: '#757494',
  neutral30: '#9C9AC1',
  neutral20: '#CBC9EF',
  neutral10: '#E8E7FF',
  white: '#fff',
  black: '#222',

  error: '#E7002A',
  success: '#3EC55F',
  warning: '#FECB2F',
  info: '#157EFB',
};

const theme = {
  colors,
  fontSizes: {
    xxl: moderateScale(32),
    xl: moderateScale(28),
    lg: moderateScale(24),
    md: moderateScale(20),
    body: moderateScale(17),
    sm: moderateScale(14),
    xs: moderateScale(12),
    xxs: moderateScale(10),
    xxxs: moderateScale(8),
  },
  spacing: {
    none: 0,
    xxs: moderateScale(4),
    xs: moderateScale(8),
    md: moderateScale(12),
    lg: moderateScale(16),
    xl: moderateScale(20),
    xxl: moderateScale(24),
    xxxl: moderateScale(28),
  },
};

export default theme;


Creating Reusable Components

Once my design tokens are in place, I define some reusable components such as Box, Typography, and Input. These components adhere to the design tokens, ensuring consistency across the app.

For example here's how I create Box component:


import {
  View,
  type ViewProps,
  type FlexAlignType,
  type ViewStyle,
} from 'react-native';
import theme from '../styles/theme/theme';

export interface IBox extends ViewProps {
  backgroundColor?: keyof typeof theme.colors;
  p?: keyof typeof theme.spacing;
  pv?: keyof typeof theme.spacing;
  ph?: keyof typeof theme.spacing;
  pt?: keyof typeof theme.spacing;
  pb?: keyof typeof theme.spacing;
  pl?: keyof typeof theme.spacing;
  pr?: keyof typeof theme.spacing;
  m?: keyof typeof theme.spacing;
  mv?: keyof typeof theme.spacing;
  mh?: keyof typeof theme.spacing;
  mt?: keyof typeof theme.spacing;
  mb?: keyof typeof theme.spacing;
  ml?: keyof typeof theme.spacing;
  mr?: keyof typeof theme.spacing;
  gap?: number;
  flex?: number;
  flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
  alignItems?: FlexAlignType;
  justifyContent?:
    | 'center'
    | 'flex-start'
    | 'flex-end'
    | 'space-between'
    | 'space-around'
    | 'space-evenly';
  rounded?: boolean;
}

export default function Box({
  backgroundColor,
  p,
  pv,
  ph,
  pt,
  pb,
  pr,
  pl,
  m,
  mv,
  mh,
  mt,
  mb,
  ml,
  mr,
  children,
  style,
  flex,
  alignItems,
  justifyContent,
  flexDirection = 'column',
  rounded = false,
  gap = undefined,
  ...rest
}: IBox) {
  const getMargin = () => {
    const obj: any = {};

    if (m) {
      obj.margin = theme.spacing[m];
      return obj;
    }
    if (mt) obj.marginTop = mt ? theme.spacing[mt] : 0;
    if (mb) obj.marginBottom = mb ? theme.spacing[mb] : 0;
    if (ml) obj.marginLeft = ml ? theme.spacing[ml] : 0;
    if (mr) obj.marginRight = mr ? theme.spacing[mr] : 0;
    if (mv) obj.marginVertical = theme.spacing[mv];
    if (mh) obj.marginHorizontal = theme.spacing[mh];
    return obj;
  };

  const getPadding = () => {
    const obj: any = {};

    if (p) {
      obj.padding = theme.spacing[p];
      return obj;
    }

    if (pt) obj.paddingTop = pt ? theme.spacing[pt] : 0;
    if (pb) obj.paddingBottom = pb ? theme.spacing[pb] : 0;
    if (pl) obj.paddingLeft = pl ? theme.spacing[pl] : 0;
    if (pr) obj.paddingRight = pr ? theme.spacing[pr] : 0;
    if (pv) obj.paddingVertical = theme.spacing[pv];
    if (ph) obj.paddingHorizontal = theme.spacing[ph];

    return obj;
  };

  const boxStyles: ViewStyle[] = [
    {
      backgroundColor: backgroundColor
        ? theme.colors[backgroundColor]
        : undefined,
      flex,
      justifyContent,
      alignItems,
      flexDirection,
      borderRadius: rounded ? 10 : 0,
      gap,
    },
    getMargin(),
    getPadding(),
    style,
  ];

  return (
    <view style="{boxStyles}">
      {children}
    </view>
  );
}


I use this newly created Box component as a replacement of View. It allows me to quickly style it through props (and give suggestions if you're using typescript) like so:

How I set up Design System for my React Native Projects for  Faster Development

Here's an example of how I create Typography component which I use instead of React Native's Text component:


import React from 'react';
import {Text, type TextProps} from 'react-native';
import theme, {FontFamily} from '../styles/theme/theme';

export interface ITypography extends TextProps {
  size?: keyof typeof theme.fontSizes;
  color?: keyof typeof theme.colors;
  textAlign?: 'center' | 'auto' | 'left' | 'right' | 'justify';
  variant?: keyof typeof FontFamily;
}

export default function Typography({
  size,
  color,
  textAlign,
  children,
  style,
  variant,
  ...rest
}: ITypography) {
  return (
    <text style="{[" color: color theme.colors : theme.colors.white textalign fontsize: size theme.fontsizes theme.fontsizes.body fontfamily: variant fontfamily fontfamily.regular>
      {children}
    </text>
  );
}


Here's a preview of how quickly I am able to add styles to my custom Typography component:

How I set up Design System for my React Native Projects for  Faster Development

Custom useTheme hook

Instead of importing theme again and again, I make my code more readable by creating a custom useTheme hook which I call anywhere in the app to add styles that adhere with my theme.

In order to do this, I leverage React's Context API to pass my theme in the app.

I create a ThemeProvider.tsx file and inside define the ThemeContext and ThemeProvider to wrap my app component inside it. Here's the code:


import React, {type PropsWithChildren, createContext} from 'react';
import theme from './theme';

export const ThemeContext = createContext(theme);

export default function ThemeProvider({children}: PropsWithChildren) {
  return (
    <themecontext.provider value="{theme}">{children}</themecontext.provider>
  );
}


Then, inside my App component:


export default function App() {
  return (
    <themeprovider>
      <appnavigation></appnavigation>
    </themeprovider>
  );
}


Now that my entire app has access to ThemeContext, I create my useTheme hook:


import {useContext} from 'react';
import {ThemeContext} from '../styles/theme/ThemeProvider';

export default function useTheme() {
  const theme = useContext(ThemeContext);
  return theme;
}


Now I can access my theme anywhere by calling the useTheme hook like so:


const theme = useTheme();
// example usage:
theme.colors.primary100;
theme.spacing.md;
theme.fontSizes.lg;


Dark Mode

To implement dark mode, in the theme.ts file, I add another color palette containing the colors for dark mode.


export const darkTheme = {
  // define dark mode colors here keeping the keys same as the light mode only changing the values.
}


Then, in ThemeProvider, I simply check user settings and switch the theme like so:


<p>import {useColorScheme} from 'react-native';</p>

<p>export default function ThemeProvider({children}: PropsWithChildren) {<br>
const isDarkMode = useColorScheme() === 'dark';<br>
  return (<br>
    <themecontext.provider value="{isDarkMode" darktheme : theme>{children}</themecontext.provider><br>
  );<br>
}</p>




Conclusion

Following this clear structured approach has brought much needed clarity, consistency, and aesthetics in my app while also sped up my development speed by at least 10x since I no longer have to dwell over design decisions.

I encourage you to try this approach and let me know what you guys think in the comments. Maybe improve it a little bit eh?

以上是我如何為我的 React Native 專案設定設計系統以加快開發速度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python vs. JavaScript:學習曲線和易用性Python vs. JavaScript:學習曲線和易用性Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python vs. JavaScript:社區,圖書館和資源Python vs. JavaScript:社區,圖書館和資源Apr 15, 2025 am 12:16 AM

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C到JavaScript:所有工作方式從C/C到JavaScript:所有工作方式Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

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脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

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