前面的话

  使用jsx语法可以实现HTML in JS,使用svgr可以实现svg in JS,使用styled-components可以实现CSS in JS。这样,使用react开发,就变成了使用JS开发,统一且方便。本文将详细介绍styled-components的用法

基本用法

【安装】

  1. $ npm install styled-components

  使用非常简单,下面的代码片段展示了 React 项目中使用 styled-components,定义了 Wrapper 和 Button 两个组件,包含了 html 结构和对应的 css 样式,从而将样式和组件之间的 class 映射关系移除

  1. import styled from 'styled-components';
  2. const Wrapper = styled.section`
  3. margin: auto;
  4. width: 300px;
  5. text-align: center;
  6. `;
  7. const Button = styled.button`
  8. width: 100px;
  9. color: white;
  10. background: skyblue;
  11. `;
  12. render(
  13. <Wrapper>
  14. <Button>Hello World</Button>
  15. </Wrapper>
  16. );

组件样式

  如果要为组件设置样式,则需要使用小括号语法,而且需要在组件上设置className和children

  1. const Link = ({ className, children }) => (
  2. <a className={className}>
  3. {children}
  4. </a>
  5. )
  6. const StyledLink = styled(Link)`
  7. color: palevioletred;
  8. font-weight: bold;
  9. `;
  10. render(
  11. <div>
  12. <Link>Unstyled, boring Link</Link>
  13. <br />
  14. <StyledLink>Styled, exciting Link</StyledLink>
  15. </div>
  16. );

  

扩展样式

  使用扩展样式,可以基于已经存在的样式进行扩展

  1. const Button = styled.button`
  2. color: palevioletred;
  3. font-size: 1em;
  4. margin: 1em;
  5. padding: .25em 1em;
  6. border: 2px solid palevioletred;
  7. border-radius: 3px;
  8. `;
  9.  
  10. const TomatoButton = Button.extend`
  11. color: tomato;
  12. border-color: tomato;
  13. `;
  14.  
  15. render(
  16. <div>
  17. <Button>Normal Button</Button>
  18. <TomatoButton>Tomato Button</TomatoButton>
  19. </div>
  20. );

更换标签

  在某些情况下,可以在复用样式的基础上更换标签

  1. const Button = styled.button`
  2. display: inline-block;
  3. color: palevioletred;
  4. font-size: 1em;
  5. margin: 1em;
  6. padding: .25em 1em;
  7. border: 2px solid palevioletred;
  8. border-radius: 3px;
  9. `;
  10. const Link = Button.withComponent('a')
  11. const TomatoLink = Link.extend`
  12. color: tomato;
  13. border-color: tomato;
  14. `;
  15. render(
  16. <div>
  17. <Button>Normal Button</Button>
  18. <Link>Normal Link</Link>
  19. <TomatoLink>Tomato Link</TomatoLink>
  20. </div>
  21. );

传递属性

  通过props可以从父组件向子组件传递属性

  1. const GlassModal = ({ children, className, backgroundColor, padding }) => (
  2. <Wrap backgroundColor={backgroundColor}>
  3. <Main padding={padding} className={className}>
  4. {children}
  5. </Main>
  6. </Wrap>
  7. )
  8. export default GlassModal
  9.  
  10. const Wrap = styled.section`
  11. background-color: ${props => props.backgroundColor || BLUE_DARK};
  12. `
  13. const Main = styled.main`
  14. padding: ${props => props.padding || ''};
  15. background-color: ${OPACITY_LIGHT};
  16. `
  1. const StyledGlassModal = styled(GlassModal)`
  2. padding: 20px 10px;
  3. text-align: center;
  4. `

  或者,基于prop来定制主题

  1. const Button = styled.button`
  2. background: ${props => props.primary ? 'palevioletred' : 'white'};
  3. color: ${props => props.primary ? 'white' : 'palevioletred'};
  4. font-size: 1em;
  5. margin: 1em;
  6. padding: .25em 1em;
  7. border: 2px solid palevioletred;
  8. border-radius: 3px;
  9. `;
  10.  
  11. render(
  12. <div>
  13. <Button>Normal</Button>
  14. <Button primary>Primary</Button>
  15. </div>
  16. );

attrs函数

  通过使用attrs函数,可以用来设置其他属性

  1. const Input = styled.input.attrs({
  2. type: 'password',
  3. margin: props => props.size || '1em',
  4. padding: props => props.size || '1em'
  5. })`
  6. color: palevioletred;
  7. border-radius: 3px;
  8. margin: ${props => props.margin};
  9. padding: ${props => props.padding};
  10. `;
  11. render(
  12. <div>
  13. <Input placeholder="A small text input" size="1em" />
  14. <Input placeholder="A bigger text input" size="2em" />
  15. </div>
  16. );

  或者引入第三方库的样式,如activeClassName

  1. const Button = styled.button.attrs({
  2. className: 'small',
  3. })`
  4. background: black;
  5. color: white;
  6. `;

  编译后的 html 结构如下:

  1. <button class="sc-gPEVay small gYllyG">
  2. Styled Components
  3. </button>

动画

  styled-components 同样对 css 动画中的 @keyframe 做了很好的支持

  1. import { keyframes } from 'styled-components';
  1. const rotate360 = keyframes`
  2. from {transform: rotate(0deg);}
  3. to {transform: rotate(360deg);}
  4. `;
  5. const Rotate = styled.div`
  6. display: inline-block;
  7. animation: ${rotate360} 2s linear infinite;
  8.  
  9. `;
  10. render(
  11. <Rotate>&lt;
  12. 使用styled-components实现CSS in JS的更多相关文章

      1. 运用 CSS in JS 实现模块化
      1. 一.什么是 CSS in JS 上图来源:https://2019.stateofcss.com/technologies/ CSS in JS 是2014年推出的一种设计模式,它的核心思想是把 CS ...

      1. 9 CSS in JS Libraries You Should Know in 2018
      1. 转自:https://blog.bitsrc.io/9-css-in-js-libraries-you-should-know-in-2018-25afb4025b9b 实际上  wix 的 styl ...

      1. styled components草根中文版文档
      1. 1.styled components官网网址 https://www.styled-components.com/docs   以组件的形式来写样式. 1.1安装 yarn add styled-c ...

      1. WebKit HTMLCSSJS
      1. 开发者需要了解的WebKit https://www.infoq.cn/article/webkit-for-developers 开发者需要了解的 WebKit   彭超 2013 年 3 月 18 ...

      1. Vue项目中引入外部文件(cssjsless
      1. 例子中css文件采用bootstrap.css,js文件采用jQuery,less文件用less.less(自定义文件) 步骤一:安装webpack cnpm install webpack -g ...

      1. vue components & `@import css` bug
      1. vue components @import css not support css3 @import https://github.com/vuejs/vue-loader/issues/138#i ...

      1. vuehtmlcssjs 分离
      1. 在正常的创建和引用vue文件都是html.css.js三者在一起的,这样写起来虽然方便了,但是页面比较大或者代码比较多的情况下,即使使用组件有时代码也比较多,简单来说查找不变不利于编程,大的来说影像优 ...

      1. vue初始化、数据处理、组件传参、路由传参、全局定义CSSJS、组件生命周期
      1. 目录 项目初始化 组件数据局部化处理 子组件 父组件 路由逻辑跳转 案例 组件传参 父传子 子组件 父组件 子传父 子组件 父组件 组件的生命周期钩子 路由传参 第一种 配置:router/index ...

      1. 6.前台项目vue环境、创建、目录重构、CSSJS配置
      1. 目录 前台 vue环境 创建项目 重构项目目录 文件修订:目录中非配置文件的多余文件可以移除 App.vue router/index.js Home.vue 全局配置:全局样式.配置文件 globa ...

    1.  
    2. 随机推荐

        1. OpenCV3计算机视觉Python语言实现笔记(三)
        1. 一.使用OpenCV处理图像 1.不同颜色空间的转换 OpenCV中有数百种关于在不同色彩空间之间转换的方法.当前,在计算机视觉中有三种常用的色彩空间:灰度.BGR以及HSV(Hue, Saturat ...

        1. vue 热加载问题
        1. 今天是使用vue突然发现没有热加载功能了,然后网上查了一下,配置了一些东西,并没有什么用,然后发现电脑FQ影响 vue 热加载 关掉FQ软件就好了,具体原理我也不清

        1. Microsoft Artificial Intelligence Conference2018.05.21
        1. 时间:2018.05.21地点:北京嘉丽大酒店

        1. linux进程管理总结
        1. 目录 一.进程相关的概念 二.关闭会话时子进程进程被杀死 三.nohup的原理 四.setsid原理 五.daemon &和守护进程的区别 六.服务进程为什么要fork两次 七.systemd ...

        1. mybatis源码-Mapper解析之SQL 语句节点解析(一条语句对应一个MappedStatement)
        1. 目录 一起学 mybatis 0 <sql> 节点解析 1 解析流程 2 节点解析 2.1 解析流程 2.2 <include> 节点的解析 2.3 Node.ELEMENT_ ...

        1. C#泛型创建实例
        1. class Test<T> where T : new() { public static T Instance() { return new T(); } } 就上面这方法, 居然比ne ...

        1. Python-TXT文本操作
        1. 一.列出IO操作的标识符及描述 标识符 描述 r 以只读方式打开文件.文件的指针将会放在文件的开头.这是默认模式. rb 以二进制格式打开一个文件用于只读.文件指针将会放在文件的开头.这是默认模式. ...

        1. Kickstart Practice Round 2017---A
        1. Problem The Constitution of a certain country states that the leader is the person with the name con ...

        1. Echatrs PIE饼图中间位置怎么显示总数值?
        1. title: { text: '总资产', subtext: '2000000.00', x: 'center', y: 'center' }图例:

        1. Column 'parent_id' specified twice
        1. Hibernate Column 'parent_id' specified twice问题解决--insertable = false, updatable = false的使用 - shendeg ...