经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » React » 查看文章
在?React?Native?中使用?CSS?Modules的配置方法
来源:jb51  时间:2022/8/1 13:09:00  对本文有异议

有些前端工程师希望也能像开发 web 应用那样,使用 CSS Modules 来开发 React Native。本文将介绍如何在 React Native 中使用 CSS Modules。

安装依赖和配置

首先安装 react-native-sass-transformer 使得我们可以在 React Native 应用中使用 sass 样式。

  1. yarn add react-native-sass-transformer sass -D

参考如下配置,修改 metro.config.js 文件

  1. const { getDefaultConfig } = require("metro-config")
  2. module.exports = (async () => {
  3. const {
  4. resolver: { sourceExts },
  5. } = await getDefaultConfig()
  6. return {
  7. transformer: {
  8. babelTransformerPath: require.resolve("react-native-sass-transformer"),
  9. },
  10. resolver: {
  11. sourceExts: [...sourceExts, "scss", "sass"],
  12. },
  13. }
  14. })()

我们还需要安装另外两个依赖

  1. yarn add babel-plugin-react-native-classname-to-style babel-plugin-react-native-platform-specific-extensions -D

修改 babel.config.js 文件,配置刚刚安装的两个插件

  1. module.exports = {
  2. presets: ["module:metro-react-native-babel-preset"],
  3. plugins: [
  4. "react-native-classname-to-style",
  5. [
  6. "react-native-platform-specific-extensions",
  7. {
  8. extensions: ["scss", "sass"],
  9. },
  10. ],
  11. ],
  12. }

因为我们的项目使用了 Typescript,为了避免类型警告,在项目中添加一个 global.d.ts 文件,内容如下

  1. declare module "*.scss"

使用

React Native CSS Modules 支持 @mixin @include @extend 等操作

  1. @mixin lightFontStyle($fontColor: rgb(0, 0, 0)) {
  2. font-size: 22px;
  3. font-family: $sencodary-font-light;
  4. letter-spacing: 0.96px;
  5. color: $fontColor;
  6. }
  7.  
  8. .input {
  9. @include lightFontStyle($fontColor: rgb(39, 39, 39));
  10. padding: 12px 20px 40px;
  11. flex: 1;
  12. }
  13.  
  14. .disabled {
  15. @extend .input;
  16. color: rgb(99, 99, 99);
  17. }

CSS Modules 也可以很好的和 StyleSheet 一起工作

  1. // App.scss
  2. @import "./theme/font.scss";
  3.  
  4. .welcome {
  5. font-family: $primary-font;
  6. font-size: 17px;
  7. text-align: center;
  8. }
  1. //App.tsx
  2. import React from "react"
  3. import { Text, StyleSheet } from "react-native"
  4. import scss from "./App.scss"
  5.  
  6. function Welcome(props: Props) {
  7. return <Text style={[scss.welcome, styles.text]}>Hello {props.name}!</Text>
  8. }
  9.  
  10. const styles = StyleSheet.create({
  11. text: {
  12. backgroundColor: "transparent",
  13. margin: 8,
  14. },
  15. })

示例

这里有 一个示例 ,供你参考。

到此这篇关于如何在 React Native 中使用 CSS Modules的文章就介绍到这了,更多相关React Native使用 CSS Modules内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号