--- tags: React Native --- # React Native ## Playground [snack - expo example practice](https://snack.expo.dev/@awu001/535c2f) ## Expo [Expo create your first app](https://docs.expo.dev/tutorial/create-your-first-app/) ## Style 1. StyleSheet.create(https://reactnative.dev/docs/style) [Cheat Sheet](https://github.com/vhpoet/react-native-styling-cheat-sheet) ``` tsx import { StatusBar } from 'expo-status-bar'; import { StyleSheet, Text, View } from 'react-native'; export default function App() { return ( <View style={styles.container}> <Text>Open up App.js to start working on your app!</Text> <StatusBar style="auto" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#25292e', alignItems: 'center', justifyContent: 'center', }, }); ``` 優: 直觀, 好上手, 無須額外設定 缺: 每個地方都要加 StyleSheet.create, 需要命名很多元件名稱 2. [NativeWind](https://www.nativewind.dev/) ``` tsx import React from 'react'; import { withExpoSnack } from 'nativewind'; import { Text, View } from 'react-native'; import { styled } from 'nativewind'; const StyledView = styled(View) const StyledText = styled(Text) const App = () => { return ( <StyledView className="flex-1 items-center justify-center"> <StyledText className="text-slate-800"> Try editing me! 🎉 </StyledText> </StyledView> ); } ``` About merging className: [clsx](https://github.com/lukeed/clsx) ``` tsx function A({ rounded, className }) { const className = clsx( "font-bold", { rounded }, variant === "primary" && "bg-blue-500 text-white", variant === "secondary" && "bg-blue-500 text-white", className ); return <B className={className} />; } ``` 優: 寫法接近 className, 建立畫面速度快, 可支援主題設定 缺: 需要熟悉有什麼 className 可以用, 需額外設定 2023/04/07 update: 目前 nativewind 似乎無法與 expo-router 相容, 詳情: https://github.com/marklawlor/nativewind/issues/419 https://github.com/marklawlor/nativewind/issues/271 3. Restyle(https://shopify.github.io/restyle/) [fixture](https://github.com/Shopify/restyle/tree/master/fixture) [5 Ways to Improve Your React Native Styling Workflow](https://shopify.engineering/5-ways-to-improve-your-react-native-styling-workflow#:~:text=5%20Ways%20to%20Improve%20Your%20React%20Native%20Styling,...%205%20%235.%20Use%20Responsive%20Style%20Properties%20) ```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, }, breakpoints: { phone: 0, tablet: 768, }, }); export type Theme = typeof theme; export default theme; ``` ```tsx import React, {useState} from 'react'; import { ThemeProvider, createBox, createText, createRestyleComponent, createVariant, VariantProps, } from '@shopify/restyle'; import {SafeAreaView, Switch} from 'react-native'; import {theme, darkTheme, Theme} from './theme'; const Box = createBox<Theme>(); const Text = createText<Theme>(); const Card = createRestyleComponent< VariantProps<Theme, 'cardVariants'> & React.ComponentProps<typeof Box>, Theme >([createVariant({themeKey: 'cardVariants'})], Box); const App = () => { const [darkMode, setDarkMode] = useState(false); const selectedTheme = darkMode ? darkTheme : theme; return ( <ThemeProvider theme={selectedTheme}> <Box backgroundColor="background" flex={1}> <SafeAreaView style={{flex: 1}}> <Box flex={1} paddingHorizontal="m" gap="s"> <Text variant="header">Welcome</Text> <Card variant="primary"> <Text variant="body"> This is a simple example displaying how to use Restyle </Text> </Card> <Card variant="secondary"> <Text variant="body"> You can find the theme in theme.ts. Update the theme values to see how it changes this screen </Text> </Card> <Card variant="primary" flexDirection="row" justifyContent="space-between" alignItems="center" > <Text variant="body">Toggle dark mode</Text> <Switch value={darkMode} onValueChange={(value: boolean) => setDarkMode(value)} /> </Card> </Box> </SafeAreaView> </Box> </ThemeProvider> ); }; export default App; ``` 優: 整體設計維持一致性, 使用方便, 支援主題設定, 文件簡單好懂 缺: 需要額外設定 個人偏好是 Restyle > StyleSheet > NativeWind >react-native#29308: In some cases React Native does not match how CSS works on the web, for example the touch area never extends past the parent view bounds and on Android negative margin is not supported. ## UI Libraries [React Native Paper](https://reactnativepaper.com/) [Mantine](https://mantine.dev/) ## State management https://jotai.org/docs/core/use-atom https://snack.expo.dev/@awu001/jotai-fetch-news-api-test ## Networking [Networking](https://reactnative.dev/docs/network) >By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. ## Image >...the bundler will bundle and serve the image corresponding to device's screen density. For example, check@2x.png, will be used on an iPhone 7, whilecheck@3x.png will be used on an iPhone 7 Plus or a Nexus 5. If there is no image matching the screen density, the closest best option will be selected. >On Windows, you might need to restart the bundler if you add new images to your project. >A caveat is that videos must use absolute positioning instead of flexGrow, since size info is not currently passed for non-image assets. This limitation doesn't occur for videos that are linked directly into Xcode or the Assets folder for Android. ## SVG [react-native-svg-transformer](https://github.com/kristerkari/react-native-svg-transformer) [React Native - how to use local SVG file (and color it)- 只支援單一顏色,多個顏色還要再研究](https://stackoverflow.com/questions/49660912/react-native-how-to-use-local-svg-file-and-color-it) ### 關於動態改變多個 svg fill 顏色 In Web: ```svg // 在特定的區塊加上 class <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle class="highlight" cx="12" cy="8" r="4" fill="currentColor" /> <rect class="highlight" x="5" y="14" width="14" height="6" rx="2" fill="currentColor" /> <path class="sketch" d="M10 14H14L13 16L14 20H10L11 16L10 14Z" fill="currentColor"/> </svg> ``` ``` const useStyles = makeStyles(() => ({ avatar: { '& .highlight': { color: #112233, }, }, })); <SvgIcon className={useStyles().avatar}> <AccountIcon /> </SvgIcon> ``` ### Network Images >Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, you will need to manually specify the dimensions of your image. Example: ``` jsx // GOOD <Image source={{uri: 'https://reactjs.org/logo-og.png'}} style={{width: 400, height: 400}} /> // BAD <Image source={{uri: 'https://reactjs.org/logo-og.png'}} /> ``` ## Testing [Test Renderer](https://reactjs.org/docs/test-renderer.html) [React Native Testing Library](https://callstack.github.io/react-native-testing-library/) >Component tests are only JavaScript tests running in Node.js environment. They do not take into account any iOS, Android, or other platform code which is backing the React Native components. It follows that they cannot give you a 100% confidence that everything works for the user. If there is a bug in the iOS or Android code, they will not find it. ## .env [dotenv](https://github.com/goatandsheep/react-native-dotenv) [react-native-config](https://github.com/luggit/react-native-config/) ## Navigation [React Navigation](https://reactnavigation.org/docs/tab-based-navigation) [Nested Navigation test](https://snack.expo.dev/@awu001/navigation-test) [expo router - File system-based routing](https://github.com/expo/router) how to move expo-router's app folder to src: https://github.com/expo/router/issues/41 ### Navigation challenges >There are a few aspects of navigation which make it challenging in React Native: > > Navigation works differently on each native platform. iOS uses view controllers, while android uses activities. These platform-specific APIs work differently technically and appear differently to the user. React Native navigation libraries try to support the look-and-feel of each platform, while still providing a single consistent JavaScript API. > >Native navigation APIs don't correspond with "views". React Native components like View, Text, and Image, roughly map to an underlying native "view", but there isn't really an equivalent for some of the navigation APIs. There isn't always a clear way to expose these APIs to JavaScript. > >Navigation on mobile is stateful. On the web, navigation is typically stateless, where a url (i.e. route) takes a user to a single screen/page. On mobile, the history of the user's navigation state is persisted in the application so that the user can go back to previous screens - a stack of screens can even include the same screen multiple times. > >Due to these challenges, there isn't a single best way to implement navigation, so it was removed from the core React Native package. ### r.g.__reanimatedWorkletlint is not a function Add useLegacyImplementation on `Drawer.Navigator` ```jsx <Drawer.Navigator useLegacyImplementation> {...} </Drawer.Navigator> ``` ## Security [Security](https://reactnative.dev/docs/security) [Expo SecureStore](https://docs.expo.dev/versions/latest/sdk/securestore/) [async-storage - 相當於瀏覽器的 LocalStorage](https://github.com/react-native-async-storage/async-storage) ## Deploy [Expo Application Services](https://docs.expo.dev/eas/) 還沒仔細看,步驟很繁瑣XD [RN Over The Air updates](https://pagepro.co/blog/react-native-over-the-air-updates/) ## Prebuild 如果你需要設定 native code, use this commend `npx expo prebuild` [Prebuild](https://docs.expo.dev/workflow/prebuild/) ## Resources [PageView - 可以左右滑動的頁面](https://github.com/callstack/react-native-pager-view) [React Native Tools - VSCode 插件](https://reactnative.dev/docs/components-and-apis) [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi) [React Native Directory - RN第三方元件庫](https://reactnative.directory/) [ImagePicker - 讓用戶上傳手機裡的圖片, 也可直接拍照](https://docs.expo.dev/versions/latest/sdk/imagepicker/) [深入了解 React Native Reanimated - 動畫效果相關](https://juejin.cn/post/7068170378123673637) [【译】Flutter vs React Native vs Native:深度性能比较](https://juejin.cn/post/6845166890524868615) [Take screenshot - 可以擷取特定的 component 畫面](https://docs.expo.dev/tutorial/screenshot/) [React Native Express - 快速複習RN](https://www.reactnative.express/) [newsLetter](https://reactnativenewsletter.com/) ## 額外補充 1. If u want to list lots of items, using [FlatList](https://reactnative.dev/docs/using-a-listview) instead of ScrollView. Because ScrollView will render all of items on it. 2. Image object-fit : resizeMode, objectFit(after RN 0.71) 3. [react-開發者一定要知道的底層架構-react-fiber](https://medium.com/starbugs/react-%E9%96%8B%E7%99%BC%E8%80%85%E4%B8%80%E5%AE%9A%E8%A6%81%E7%9F%A5%E9%81%93%E7%9A%84%E5%BA%95%E5%B1%A4%E6%9E%B6%E6%A7%8B-react-fiber-c3ccd3b047a1) 4. [一文搞懂 React 18 中的 useTransition()](https://www.jb51.net/article/262378.htm) 5. [React18中的useDeferredValue示例详解](https://www.jb51.net/article/241012.htm)