在 create-react-app构建项目时使用css-modlue解决样式冲突

1.0 理解css-modlue是什么

CSS-Module 是一个 css 模块化解决方案,可以通过webpack 在 css-loader 配置 css-module ,开启后默认局部作用域

2.0 为什么要使用css-modlue

通过模块化的方式引入css,这样引入的样式名称会根据一定算法给名称加以修改,防止在引入其他组件的时候样式会冲突
在这里插入图片描述

3.0 如何使用,以及应用场景

模块化方式引入css : import style from './index.module.sass',在使用的时候就通过 style.xxx 的方式获取样式

4.0 案例展示

样式: index.module.sass,注意: global的使用

.home {
    height: 100%;
  }
  
  .home {
    // 在css-modules 中使用 :global包裹起来的代码,不会被重新命名
    :global {
      .am-tab-bar {
        position: fixed;
        width: 100%;
        height: 50px;
        bottom: 0;
      }
    }
  }
  
  .tabbar{
    :global{
      .iconfont {
        font-size: 20px;
      }
    }
  }

home.jsx的代码

// 1.0 模块化导入样式
  import style from './index.module.scss'
// 2.0 在组件的render()函数中使用:
  render() {
    return (
      <div className={style.home}>
        {/* Route 占位以及路由匹配 */}
        <Route exact path="/home" component={Index} />
        <Route path="/home/list" component={HouseLists} />
        <Route path="/home/news" component={News} />
        <Route path="/home/profile" component={Profile} />
        <div className={style.tabbar}>{this.renderTabBar()}</div>
      </div>
    )
  }

5.0 注意点是什么

css-modules 中使用 :global包裹起来的代码,不会被重新命名,往往那些字体的样式名 以及 使用到第三方的UI组件时候 我们并不希望重新命名
在create-react-app中要使用sass一定要安装 node-sass 、sass-loader

发布了102 篇原创文章 · 获赞 14 · 访问量 7067

猜你喜欢

转载自blog.csdn.net/weixin_42060658/article/details/104354780
今日推荐