加载中...
  • styled-components的配置和使用

    在react中,正常的给组件引入css文件,该css文件会直接作用于全局,使用styled-components可以有效控制好css作用域

    首先我们需要安装

    1
    npm install --save styled-components

    配置并设置全局样式,新建一个js文件,style.js,使用createGlobalStyle创建全局样式。

    1
    2
    3
    4
    5
    6
    7
    import { createGlobalStyle } from 'styled-components'

    export const GlobalStyle = createGlobalStyle`
    body {
    background:red
    }
    `

    使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import React, { Component } from 'react';
    import { GlobalStyle } from "./style";

    class App extends Component {
    render() {
    return (
    <div>
    <GlobalStyle/>
    hello world
    </div>
    );
    }
    }

    export default App;

    局部样式,引入styled-components,设置一个div的样式,导出HeaderWrapper

    1
    2
    3
    4
    5
    6
    import styled  from 'styled-components'

    export const HeaderWrapper = styled.div`
    height: 56px;
    background: red;
    `

    引入style的HeaderWrapper,此时该标签其实是一个带有样式的div标签,将他作为一个标签替换原本render内的最外层div

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import React, { Component } from 'react'
    import {
    HeaderWrapper
    } from "./style";

    class Header extends Component {
    render() {
    return (
    <HeaderWrapper>
    header
    </HeaderWrapper>
    )
    }
    }

    export default Header

    为了防止过度组件化,我们可以在局部里面写class代码
    如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    const Wrapper = styled.div`
    /* 将Wrapper组件里的color设置为白色 */
    padding-left: 50px;
    background: black;
    color: white;

    /* 将Wrapper组件里的h3标签的color设置为红色 */
    h3 {
    color: red
    }
    /* 将Wrapper组件里的className为black的标签的color设置为黄色 */
    .yellow {
    color: yellow
    }
    `

    render(
    <Wrapper>
    <p>白色 p 标签 </p>
    <h3>红色 h3 标签</h3>
    <p className="yellow" >黄色 p 标签</p>
    </Wrapper>
    )

    RCXy9S.png

    借鉴自:https://blog.csdn.net/scorpio_h/article/details/86754165
    https://www.jianshu.com/p/20215e035160

    上一篇:
    react暴露webpack配置文件
    下一篇:
    uni-app 整包升级/更新方案
    本文目录
    本文目录