现代前端指南!

react之styled-components

2020-08-06  本文已影响0人  雨落倾城夏微凉_e861

最近做项目用到了一个样式框架,感觉非常好用,在此,记录一下它常用的一些用法。
github地址:https://github.com/styled-components/styled-components

最大的特点就是既可以写组件的样式,也可以作为一个react组件来使用,同样写一些小栗子来了解一下。

安装

npm install styled-components 或
cnpm install styled-components 或
yarn add styled-components

引入

import styled from "styled-components"

基本用法:

const ContextBox = styled.div`
    width: 200px;
    height: 200px;
    background: red;
`
export default function(){
    return (
        <ContextBox></ContextBox>
    )
}

打开页面看效果


1.png

给子元素设置样式

const ContextBox = styled.div`
    width: 200px;
    height: 200px;
    background: red;
    p {
        font-size: 24px;
        color: #fff;
        text-align: center;
    }
    &::after {
        display: block;
        content: "hello world";
        font-size: 30px;
    }
`
export default function(){
    return (
        <ContextBox>
            <p>styled-components</p>
        </ContextBox>
    )
}

查看效果


2.png

嵌套继承样式:

const Mainstyle = styled.div`
    span {
        font-size: 14px;
        color: yellow;
    }
`
const ContextBox = styled(Mainstyle)`
    width: 200px;
    height: 200px;
    background: red;
    p {
        font-size: 24px;
        color: #fff;
        text-align: center;
    }
    &::after {
        display: block;
        content: "hello world";
        font-size: 30px;
    }
`
export default function(){
    return (
        <ContextBox>
            <p>styled-components</p>
            <span>这是一个span标签</span>
        </ContextBox>
    )
}

页面效果:


3.png

变量控制样式:

//引入css
import styled, {css} from "styled-components"
const Mainstyle = styled.div`
    span {
        font-size: 14px;
        color: yellow;
    }
`
const ContextBox = styled(Mainstyle)`
${({num, color}) => css`
    width: 200px;
    height: 200px;
    background: ${color};
    p {
        font-size: 24px;
        color: #fff;
        text-align: center;
    }
    &::after {
        display: block;
        content: "hello world";
        font-size: ${num}px;
    }
`}`
export default function(){
    return (
        <ContextBox num={16} color="green">
            <p>styled-components</p>
            <span>这是一个span标签</span>
        </ContextBox>
    )
}
4.png
上一篇 下一篇

猜你喜欢

热点阅读