網站首頁 編程語言 正文
有些前端工程師希望也能像開發 web 應用那樣,使用 CSS Modules 來開發 React Native。本文將介紹如何在 React Native 中使用 CSS Modules。
安裝依賴和配置
首先安裝?react-native-sass-transformer?使得我們可以在 React Native 應用中使用 sass 樣式。
yarn add react-native-sass-transformer sass -D
參考如下配置,修改 metro.config.js 文件
const { getDefaultConfig } = require("metro-config") module.exports = (async () => { const { resolver: { sourceExts }, } = await getDefaultConfig() return { transformer: { babelTransformerPath: require.resolve("react-native-sass-transformer"), }, resolver: { sourceExts: [...sourceExts, "scss", "sass"], }, } })()
我們還需要安裝另外兩個依賴
yarn add babel-plugin-react-native-classname-to-style \ babel-plugin-react-native-platform-specific-extensions -D
修改 babel.config.js 文件,配置剛剛安裝的兩個插件
module.exports = { presets: ["module:metro-react-native-babel-preset"], plugins: [ "react-native-classname-to-style", [ "react-native-platform-specific-extensions", { extensions: ["scss", "sass"], }, ], ], }
因為我們的項目使用了 Typescript,為了避免類型警告,在項目中添加一個 global.d.ts 文件,內容如下
declare module "*.scss"
使用
React Native CSS Modules 支持?@mixin @include @extend
?等操作
@mixin lightFontStyle($fontColor: rgb(0, 0, 0)) { font-size: 22px; font-family: $sencodary-font-light; letter-spacing: 0.96px; color: $fontColor; } .input { @include lightFontStyle($fontColor: rgb(39, 39, 39)); padding: 12px 20px 40px; flex: 1; } .disabled { @extend .input; color: rgb(99, 99, 99); }
CSS Modules 也可以很好的和 StyleSheet 一起工作
// App.scss @import "./theme/font.scss"; .welcome { font-family: $primary-font; font-size: 17px; text-align: center; }
//App.tsx import React from "react" import { Text, StyleSheet } from "react-native" import scss from "./App.scss" function Welcome(props: Props) { return <Text style={[scss.welcome, styles.text]}>Hello {props.name}!</Text> } const styles = StyleSheet.create({ text: { backgroundColor: "transparent", margin: 8, }, })
示例
這里有?一個示例?,供你參考。
原文鏈接:https://juejin.cn/post/7126729625438257159
相關推薦
- 2022-05-19 C++實現職工工資管理系統課程設計_C 語言
- 2022-06-01 AndriodStudio利用ListView和數據庫實現簡單學生管理_Android
- 2022-11-10 android時間選擇控件之TimePickerView使用方法詳解_Android
- 2024-03-07 MyBatis多表映射
- 2022-08-19 Python運行時修改業務SQL代碼_python
- 2022-08-10 C語言如何在字符數組中插入一個字符_C 語言
- 2022-04-16 python代碼有一行標黃問題的解決方案_python
- 2023-07-09 .Net下驗證MongoDB 的 Linq 模式聯合查詢是否可用
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支