React样式模块化解决方案--styled-components_react styled-components-程序员宅基地

技术标签: react  

介绍

styled-components是一个css in js 类库。

可以防止css样式污染、组件更改时更容易定位到相关的样式。

它使用标签模板来对组件进行样式化。它移除了组件的样式之间的映射。这意味着,当你定义一个样式时,实际上只是创建了一个普通的React组件,定义的样式也附在它上面。

由于React对css的封装非常弱,导致了一系列第三方库,用来加强React的CSS操作(统称 CSS in JS,使用JS语言写CSS)

另一个CSS in JS库 polished

起步

1、创建react项目

2、yarn add styled-components 、npm install --save styled-components

基本用法

import styled from 'styled-components'
import styled from 'styled-components'

const Container = styled.div`
  background-color : #f60;
  border : 10px solid #f60;

`
export default Container;

import Container from './basic/index'
import P from './basic/detals'
import './App.css';

function App() {
    
  return (
    <div className="App">
      <Container>
        <P>
        哈哈
        </P></Container>
    </div>
  );
}

export default App;

import styled from 'styled-components'

const P = styled.p`
  background-color : #f00;
  font-size:24x;

`
export default P;

基于props做样式判断

import styled from 'styled-components'
import {
     Button } from 'antd'


const StyleButton = styled(Button)`
  background-color:${
      props => (props.error?"red":'blue')};
  color:#fff;
  border:${
      props =>(props.border?"2px solid black":"none")}
`
export default StyleButton

也可以使用CSS定义一个样式,然后根据属性判断。

import styled ,{
     css } from 'styled-components'
import {
     Button } from 'antd'

const extraCss = css`
  font-size:20px;
  background:#f6a;
  padding:20px;
  border:10px solid red;
`


const StyleButton = styled(Button)`
  background-color:${
      props => (props.error?"red":'blue')};
  color:#fff;
  border:${
      props =>(props.border?"2px solid black":"none")};
  ${
      props => props.widthborder && extraCss}
`
export default StyleButton

使用(注意:属性不能使用驼峰的形式)

  <StyleButton>button</StyleButton>
  <StyleButton error='true'>error btn</StyleButton>
  <StyleButton border='true'>border btn</StyleButton>
  <StyleButton widthborder='true'>width btn</StyleButton>

还能直接传入一个样式属性。

const StyleButton = styled(Button)`
  background-color:${
      props => (props.error?"red":'blue')};
  color:#fff;
  border:${
      props =>(props.border?"2px solid black":"none")};
  min-width:${
      props => props.minwidth || 200}px;
  ${
      props => props.widthborder && extraCss}
`

样式扩展

当组件库样式不满足时

import styled from 'styled-components'
import {
     Button } from 'antd'

const ExpendBtn = styled(Button)`
  color:red;
  border:3px solid red;
`
export default ExpendBtn

如果想要组件重新渲染,可以使用as属性。假设使用标签来渲染 ExpendBtn组件。

 <ExpandBtn as="a" href='http://www.baidu.com'>expand as </ExpandBtn>

自定义组件样式

import styled from 'styled-components'

const Div = ({
    className , children})=> <div className={
    className}>{
    children}</div>

const CustomDiv = styled(Div)`
  color:red;
  border:3px solid red;
`
export {
    CustomDiv,Div} 

使用.attrs API为组件添加样式

import styled from "styled-components";

const PasswordInput = styled.input.attrs({
    
  type: "password",
  margin: props => props.size || "1em",
  padding: props => props.size || "1em"
})`
  color: palevioletred;
  font-size: 1em
`;

export default PasswordInput;

动画

keyframes API

import styled ,{
     keyframes } from "styled-components";

const rotateStyle = keyframes`
  from{
    transform: rotate(0deg)
  }
  to{
    transform:rotate(360deg)
  }
`

const RotateCom = styled.div`
  display:inline-block;
  background:#f60;
  width:100px;
  height:100px;
  animation:${
      rotateStyle} 2s linear infinite;
`
export default RotateCom

父组件中 定义子组件样式

1、通过tag名

const Wrapper = styled.div`
	width:220px;
  > h1{
		color:red
  }
`

2、通过组件名来查找

const Wrapper = styled.div`
	width:220px;
  ${Child}{
		color:red
  }
`

这里的组件只能是Styled方式定义的。

优先级

使用&&

const Custom = styled(Button)`
	&& {
		width:200px;
	}
`

参考

官网

StyledComponents

react css解决方案

styled-componts

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/guo187/article/details/112970074

智能推荐

linux命令之yum、screen_yum screen-程序员宅基地

文章浏览阅读5.1k次,点赞4次,收藏4次。一、yum命令安装程序screen[root@localhost ~]# yum install screen -y解释:-y表示中间有提示的地方都选择yes,也可以不加-y参数卸载程序screen[root@localhost ~]# yum remove screen -y查看程序screen的信息[root@localhost ~]# yum info screen显示程序..._yum screen

android 夜神,全球首个安卓9模拟器即将问世-程序员宅基地

文章浏览阅读606次。夜神模拟器在模拟器行业率先破圈,即将全球首发安卓9 内核模拟器,目前已确认可运行《原神》、《盾之勇者成名录RERISE》等需要安卓8以上环境才能运行的热门手游。强劲的市场表现,离不开技术的深耕。在过去一年多时间里,夜神模拟器团队专注于安卓9架构进行研究与适配,并深入安卓模拟器内核,适配Windows指令编码,进行深度优化,终于解决了困扰很多大型3D游戏玩家的难题。据悉,NOX旗下夜神模拟器团队成立..._夜神模拟器无法安装安卓9

Linux-4.x_x _64 内核配置选项简介_config_procd_zram_tmpfs-程序员宅基地

文章浏览阅读7.4k次,点赞2次,收藏9次。Gentoo LinuxGentoo内核(gentoo-sources)特有的选项Gentoo Linux supportCONFIG_GENTOO_LINUX选"Y"后,将会自动选中那些在Gentoo环境中必须开启的内核选项,以避免用户遗漏某些必要的选项,减轻一些用户配置内核的难度.建议选"Y".Linux dynamic and persistent device naming (usersp..._config_procd_zram_tmpfs

split( ' / ', 1)[:] , os.path.split( ) 与 os.path.splitext( ' / ', 1)[:]_split('\\', 1)[1]-程序员宅基地

文章浏览阅读366次。https://www.cnblogs.com/fengff/p/9294397.htmlos.path.splitext(filePath) [0]分离文件路径与文件名 返回第一部分_split('\\', 1)[1]

Android代码异常Calling a method in the system process without a qualified user-程序员宅基地

文章浏览阅读1.3w次。Android代码异常Calling a method in the system process without a qualified user_calling a method in the system process without a qualified user

winform上位机实例_雅马哈RCX340机器人与相机实例程序说明-程序员宅基地

文章浏览阅读763次。雅马哈RCX340机器人与相机实例程序说明1.0 海康威视的摄像头配合雅马哈的机器人,在柔性上料盘中取料,然后放置到料盒中CLOSE GP0'-----------复位TCP通讯OPEN GP0 '-----------------------打开TCP通讯Z!=91.151'--------取料Z深度Z2!=57.162'--------放料Z深度P3=P11'------P11为原始放料位S..._c# yamaha rcx

随便推点

二维旋转矩阵公式推导_二阶矩阵的旋转变换公式是啥-程序员宅基地

文章浏览阅读1.5w次,点赞4次,收藏18次。这篇博文来推导一下旋转矩阵。首先来假设 OP1旋转到了OP2,逆时针矩阵推导。当然也有顺时针矩阵推导。然后有没有什么办法可以不考虑顺时针逆时针?这里我考虑了一下OP1和OP2不相等的情况因为先求的sin(theta),如果是逆时针,theta就是正值,如果是顺时针,theta就是负值。之前我的想法,求theta,是先根据三角形的边长求夹角的公式求的cos(theta)..._二阶矩阵的旋转变换公式是啥

五款出色的产品原型设计工具推荐-程序员宅基地

文章浏览阅读808次,点赞16次,收藏23次。传统的产品原型设计工具不仅会使计算机频繁“闪光”,而且非常“懒惰”,使设计效率自动扶梯下降!基于云运行的新一代在线协作产品原型设计工具的即时设计,无论是在设计层功能还是内存配置要求上,都完美地实现了高效产品原型设计的工作理念,无需下载即可使用,一键交付,支持多层同步设计,“云”、“通用性”、“协作”一统拿下!导入Axure格式扭曲乏味?别担心!产品原型设计工具即时设计的[Axure演示文件]格式功能可以一键导入Axure文件HTML静态格式,100%保留交互效果。

grid安装时 ssh配置无法通过_/usr/bin/scp.orig -t $*-程序员宅基地

文章浏览阅读348次,点赞10次,收藏6次。Apply patch 30159782 before run "gridSetup.sh", see (Doc ID 1410202.1) for how to apply OneOff patch before run "gridSetup.sh". gridSetup.sh -applyRU OR use below workaround.Workaround : (if your unix admin allows it)Before insta_/usr/bin/scp.orig -t $*

设计一个程序,其中有三个类,CBank,BBank,GBank._编写一个的程序,其中有两个类:abank和cbank,分别表示农业银行类和中国银行类。每-程序员宅基地

文章浏览阅读5.8k次,点赞9次,收藏33次。设计一个程序,其中有三个类,CBank,BBank,GBank. 分别为中国银行类,工商银行类,农业银行类。每个类都包含一个私有数据balance,用于存放储户在该行的存款数,另有一个友元函数total,用于计算储户在这3家银行中的总存款数。#include <iostream> using namespace std;class CBank //中国银行类{..._编写一个的程序,其中有两个类:abank和cbank,分别表示农业银行类和中国银行类。每

【Unity3D开发小游戏】《植物大战僵尸游戏》Unity开发教程_植物大战僵尸环境unity创建-程序员宅基地

文章浏览阅读1.4w次,点赞31次,收藏166次。一、前言今天我们要用Unity3D做一个植物大战僵尸的仿制版本。为了保持简单,我们将忽略所有花哨的东西,如菜单,多层次或剪裁场景,并专注于在后院与僵尸作战。以下是游戏的预览:二、版本Unity5.0.1f1三、正文1.主摄像机设置如果我们选择主照相机在层次性然后我们可以设置背景色若要黑色,请调整大小而位置如下图所示:2.创造草木注意:右击图像,选择另存为.。,保存到项目的资..._植物大战僵尸环境unity创建

Python 算法基础篇:递归的概念与原理_python里递归的原理-程序员宅基地

文章浏览阅读149次。递归是一种强大的编程技术,它允许函数在执行过程中调用自身。递归在解决许多问题时非常有效,例如数学中的阶乘和斐波那契数列等。本篇博客将介绍递归的概念与原理,并通过实例代码演示它们的应用。_python里递归的原理