• React使用Styled-Componets来添加样式


    React使用Styled-Componets来添加样式


    Styled-Comonents是用JS中ES6
    语法的方式来管理CSS样式的一个组件,解决了在import CSS文件时样式重复

    安装


    1. 项目根目录下打开bash
    yarn add styled-components


    1. 新建一个style.js文件来添加样式

    注意,这里不是用style.css文件。

    使用


    style.js

    /*
     * @Author: YooHoeh 
     * @Date: 2018-07-17 16:23:09 
     * @Last Modified by: YooHoeh
     * @Last Modified time: 2018-07-18 16:43:05
     * @Description: 
     */
    
    import styled from "styled-components";
    import logoPic from "../../statics/logo.png";
    
    export const HeaderWrapper = styled.div` //导出以一个组件名为HeaderWrapper的样式,
      position: reletive;
      height: 56px;
      // background: red;  //支持添加//来添加注释,这行样式将不会执行
      border-bottom: 1px solid #f0f0f0f0;
    `;
    
    export const Logo = styled.a.attrs({
      href: "/"     //通过attrs()方法为组件添加其他属性
    })`
        100px;
      background: url(${logoPic});    //只能使用import的方式将图片导入,不能填写直接填写本地路径
    
    `;

    index.js

    /*
     * @Author: YooHoeh 
     * @Date: 2018-07-17 16:18:56 
     * @Last Modified by: YooHoeh
     * @Last Modified time: 2018-07-18 17:48:48
     * @Description: 
     */
    
    import 
    '''''';
    import {
      HeaderWrapper,
      Logo
      } from "./style";
    
    export default class Header extends Component {
     ''''
      render() {
         return (
          <HeaderWrapper>   //这里用style.js中对应的组件名,渲染的时候会替换成对应的标签类型。
            <Logo />
          </HeaderWrapper>
        );
      }
    }
    

    进阶用法


    子代选择

    index.js

        <Item >
          <input className='active'/>
          <input/>
          <input/>
        </Item >
    

    style.js

        const Item = styled.div`
        font-size:15px;
        .active{   //和Sass格式一样,在里面可以直接添加可以表示子代拥有
          border:1px solid red;
        }
        `

    多Class名选择

    index.js

        <Item className='item active'>1</Item >
        <Item className='item'>2</Item >

    style.js

        const Item = styled.div`
        font-size:15px;
        &.active{   //添加&可以表示同时拥有
          color:red;
        }
        `
  • 相关阅读:
    DataTable用中使用Compute 实现简单的DataTable数据的统计
    绑定生成一个有树结构的下拉菜单
    Docker--UI管理-----------Portainer安装部署使用
    调整系统的inode数量
    配置Linux服务器从第三方 SMTP 服务器外发邮件
    Jenkins的用户角色权限管理
    shell脚本----MongoDB4.0.21一键安装
    Shell----监控CPU/内存/负载高时的进程
    MySQL配置参数优化
    shell脚本实现---Zabbix5.0快速部署
  • 原文地址:https://www.cnblogs.com/YooHoeh/p/9334406.html
Copyright © 2020-2023  润新知