【React】局部样式

转:https://www.dazhuanlan.com/sodeath/topics/1178217

react的局部样式相比vue要麻烦点,vue可以在style标签上添加scoped,达到使样式作用于当前文件的效果,而react没有,但是react有其他的实现方式,比如我所知道且使用过的css-Modulesstyled-components

css-Modules

自动为每一个类生成一个哈希值,产生惟一标志,因此避免了类的覆盖,如下图:

css-modules

这里需要配置wepack文件,react项目需要执行npm eject命令暴露出config文件,配置如下:

{
  test: /.css$/,
  exclude: [/node_modules/, /static/],
  use: getStyleLoaders({
    importLoaders: 1,
    modules: true,
    localIdentName: '[name]_[local]_[hash:base64:5]'
  }),
},

其中的/static/是一些 css 全局的文件

关键配置就是 modules: true

styled-components

styled-components是常用的css in js类库,他有很多的语法,传送门,它会在每个标签上生成唯一的类名,如下:

styled-components

这里需要在项目中引入styled-components,安装完成之后可以在需要的目录下创建如style.js文件,并在其中引入styled-components,使用如下:

style.js

 import styled  from 'styled-components';

 export const ModeDiv = styled.a.attrs({
  
  href: 'javascript:;'
 })`
  float: right;
  line-height: 56px;
  height: 56px;
  padding: 0 10px 0 15px;
  color: #969696;
  text-decoration: none;
  .icon-Aa {
    font-size: 24px;
  }
`
...

export const NavItem = styled.div`
  float: left;
  line-height: 56px;
  font-size: 16px;
  color: #777;
  margin-right: 40px;
  .icon {
    font-size: 20px;
    vertical-align: top;
    margin-right: 2px;
  }
  &.first {
    color: #EA6F5A;
  }
  &.third {
    position: relative;
  }
  .icon-fangdajing {
    position: absolute;
    top: 2px;
    right: 10px;
    z-index: 10px;
  }
  .focused {
    display: inline-block;
    background: #969696;
    color: #fff;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    text-align: center;
    line-height: 32px;
    top: 14px;
    right: 5px;
    cursor: pointer;
  }
  .slide-enter {
    transition: all .2s ease-out;
  }
  .slide-enter-active {
    width: 260px;
  }
  .slide-exit {
    transition: all .2s ease-out;
  }
  .slide-exit-active {
    width: 160px;
  }
`

index.jsx


 import { ModeDiv, NavItem } from './style';
 import { CSSTransition } from 'react-transition-group';


  


...


  
    
       handleFocus(list)}
        onBlur={handleBlur}>
      
    
  
  {(() => {
    if (focused || mouseIn) {
      return searchWrap();
    }
    return null
  })()}

你可能感兴趣的:(【React】局部样式)