日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

在?React?Native?中使用?CSS?Modules的配置方法_React

作者:todoit ? 更新時間: 2022-09-26 編程語言

有些前端工程師希望也能像開發 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

欄目分類
最近更新