当前位置:首页 > React

react项目如何使用rem

2026-01-24 22:29:08React

使用 rem 的配置方法

在 React 项目中配置 rem 单位适配移动端,可以通过以下方式实现:

安装 postcss-pxtorem 插件

npm install postcss-pxtorem --save-dev

配置 craco 覆盖 create-react-app 默认配置(如使用 CRA)

npm install @craco/craco --save

创建 craco.config.js 文件

module.exports = {
  style: {
    postcss: {
      plugins: [
        require('postcss-pxtorem')({
          rootValue: 16,
          propList: ['*']
        })
      ]
    }
  }
}

动态计算 rem 基准值

在 public/index.html 的 head 中添加脚本

<script>
  document.documentElement.style.fontSize = 
    Math.min(window.innerWidth, 750) / 750 * 100 + 'px'
</script>

或在 src/index.js 中添加 resize 事件监听

function setRem() {
  const docEl = document.documentElement
  const width = Math.min(docEl.clientWidth, 750)
  docEl.style.fontSize = width / 7.5 + 'px'
}
window.addEventListener('resize', setRem)
setRem()

CSS 中使用 rem 单位

设置基础样式

body {
  font-size: 16px; /* 1rem = 16px */
}

.container {
  width: 10rem; /* 160px */
  padding: 0.5rem; /* 8px */
}

设计稿尺寸转换

假设设计稿宽度为 750px,开发时可直接按设计稿尺寸书写

react项目如何使用rem

// postcss-pxtorem 配置
{
  rootValue: 75,
  unitPrecision: 5,
  propList: ['*'],
  selectorBlackList: [],
  replace: true,
  mediaQuery: false,
  minPixelValue: 0
}

注意事项

使用 rem 布局时需确保所有尺寸单位统一为 rem
媒体查询中的尺寸也需要转换为 rem 单位
某些第三方组件可能需要单独处理样式覆盖
SVG 等矢量图形建议仍使用 px 单位保持清晰度

分享给朋友:

相关文章

如何搭建react项目

如何搭建react项目

使用 Create React App 搭建项目 Create React App (CRA) 是官方推荐的快速搭建 React 项目的工具,无需配置构建工具(如 Webpack 或 Babel)。…

react项目如何调试

react项目如何调试

使用浏览器开发者工具 React项目调试最直接的方法是使用浏览器内置的开发者工具(Chrome DevTools/Firefox Developer Tools)。打开开发者工具后,切换到“Sourc…

hashrouter如何使用react

hashrouter如何使用react

使用 HashRouter 在 React 中的方法 安装 react-router-dom 确保项目中已安装 react-router-dom,若未安装,可通过以下命令安装: npm inst…

react如何接入项目

react如何接入项目

创建React项目 使用create-react-app快速初始化项目: npx create-react-app my-app cd my-app npm start 适用于全新项目,自动配置…

vue实现echarts项目

vue实现echarts项目

vue3 中集成 ECharts 安装 ECharts 依赖包 npm install echarts --save 在组件中引入并初始化 import * as echarts from 'ec…

vue项目实现打印

vue项目实现打印

Vue 项目中实现打印功能 在 Vue 项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法: 使用 window.print() 方法 最简单的打印方式是调用浏览器的 window.pri…