React中样式私有化处理styled-components

57 阅读1分钟

#使用styled-components 下载

  • yarn add styled-components
  • npm install styled-components

1.分文件样式

  • 样式文件NavStyle.js
import styled from "styled-components";
import { colorRed, colorBlue, titleSize } from './common';

/*
 基于 “styled.标签名” 这种方式编写需要的样式
   + 样式要写在“ES6模板字符串”中
   + 返回并且导出的结果是一个自定义组件

 如果编写样式的时候没有提示,我们可以在vscode中安装一个官方插件:vscode-styled-components
 */
export const NavBox = styled.nav`
    background-color: lightblue;
    width: 300px;

    .title{
        font-size: ${titleSize};
        color: ${colorRed};
        line-height: 40px;

        &:hover{
            color: ${colorBlue};
        }
    }
`;

export const NavBarBox = styled.div.attrs(props => {
    return {
        size: props.size || 16
    }
})`
    line-height: 40px;

    a{
        font-size: ${props => props.size}px;
        color: #000;
        margin-right: 10px;

        &:hover{
            color: ${props => props.hover};
        }
    }
`;
  • nav文件使用样式
import React from "react";
import { NavBox, NavBarBox } from './NavStyle';

const Nav = function Nav() {
    return <NavBox>
        <h2 className="title">购物商城</h2>
        <NavBarBox hover="#ffe58f">
            <a href="/home">首页</a>
            <a href="/rush">秒杀</a>
            <a href="/my">我的</a>
        </NavBarBox>
    </NavBox>;
};

export default Nav;

2.使用公共样式

  • 编写公共样式文件common.js
import styled from "styled-components";

/* 编写一些通用的样式 */
export const colorRed = "#ff4d4f";
export const colorBlue = "#1677ff";
export const titleSize = "18px";

export const CommonListBox = styled.ul`
    box-sizing: border-box;
    padding: 10px;
    border: 1px solid #999;

    li{
        font-size: 14px;
        line-height: 30px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        &:hover{
            color: ${colorRed};
        }
    }
`;
  • 使用公共样式
import React from "react";
import styled from "styled-components";
import { CommonListBox, titleSize, colorRed } from './common';
/* 编写组件的样式:基于CSS-IN-JS思想中的styled-components插件 */
const MenuBox = styled.div`
    background-color: lightpink;
    width: 400px;

    .title{
        font-size: ${titleSize}px;
        line-height: 40px;

        &:hover{
            color: ${colorRed};
        }
    }

    li{
        font-size: 16px !important;
    }
`;

class Menu extends React.Component {
    render() {
        return <MenuBox>
            <h2 className="title">产品分类列表</h2>
            <CommonListBox>
                <li>手机</li>
                <li>电脑</li>
                <li>家电</li>
            </CommonListBox>
        </MenuBox>;
    }
};

export default Menu;