styled-components 的用法

2023-11-19

用于给标签或组件添加样式

给标签或组件添加样式

import styled from 'styled-components'

// styled.button : 给button标签添加样式 
const Button = styled.button`
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
`

// styled(Button) : 给Button组件添加样式 
const TomatoButton = styled(Button)`
  background: tomato;
`

render(
  <>
    <Button>I'm purple.</Button>
    <br />
    <TomatoButton>I'm red.</TomatoButton>
  </>
)

在这里插入图片描述

通过变量赋值

import styled from 'styled-components'

const padding = '3em'

const Section = styled.section`
  color: white;

  /* Pass variables as inputs */
  /* 使用变量赋值 */
  padding: ${padding};

  /* Adjust the background from the properties */
  /* 通过props改变背景 */
  background: ${props => props.background};
`

render(
  <Section background="cornflowerblue">
    ✨ Magic
  </Section>
)

![在这里插入图片描述](https://img-blog.csdnimg.cn/e75a88885202495db69e74f35fcb0e89.png

同时设置属性和样式

import styled from 'styled-components'

const Input = 
	styled.input.attrs(props => ({
	  type: 'text',
	  size: props.small ? 5 : undefined,
	}))
	`
	  border-radius: 3px;
	  border: 1px solid palevioletred;
	  display: block;
	  margin: 0 0 1em;
	  padding: ${props => props.padding};
	
	  ::placeholder {
	    color: palevioletred;
	  }
	`

render(
  <>
    <Input small placeholder="Small" />
    <Input placeholder="Normal" />
    <Input padding="2em" placeholder="Padded" />
  </>
)

在这里插入图片描述

临时的props

防止样式组件使用的props传递给Dom元素或其底层React节点,可以使用$标识一个只用于样式的临时props属性

const Comp = styled.div`
  color: ${props =>
    props.$draggable || 'black'};
`;

render(
  <Comp $draggable="red" draggable="true">
    Drag me!
  </Comp>
);

在这里插入图片描述

shouldForwardProp

通过数组过滤不需要透传的props属性,!['hidden'].includes(prop)

const Comp = 
styled('div')
.withConfig({
  shouldForwardProp: (prop, defaultValidatorFn) =>
      !['hidden'].includes(prop)
      && defaultValidatorFn(prop),
})
.attrs({ className: 'foo' })
`
  color: red;
  &.foo {
    text-decoration: underline;
  }
`;

render(
  <Comp hidden draggable="true">
    Drag Me!
  </Comp>
);

在这里插入图片描述

ThemeProvider

用于注入主题的辅助组件

import styled, { ThemeProvider } from 'styled-components'

const Box = styled.div`
  color: ${props => props.theme.color};
`

render(
  <ThemeProvider theme={{ color: 'mediumseagreen' }}>
    <Box>I'm mediumseagreen!</Box>
  </ThemeProvider>
)

在这里插入图片描述

直接添加样式,不生成多余的组件

前提:配置Babel

<div
  css={`
    background: papayawhip;
    color: ${props => props.theme.colors.text};
  `}
/>

<Button
  css="padding: 0.5em 1em;"
/>

Babel会把带有css属性的元素转换为样式组件

import styled from 'styled-components';

const StyledDiv = styled.div`
  background: papayawhip;
  color: ${props => props.theme.colors.text};
`

const StyledButton = styled(Button)`
  padding: 0.5em 1em;
`

<StyledDiv />
<StyledButton />

createGlobalStyle

生成全局样式的辅助函数

import { createGlobalStyle } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
  }
`

// later in your app

<React.Fragment>
  // 放在React树的顶端,当组件被渲染时,全局样式就会被注入
  <GlobalStyle whiteColor />
  
  <Navigation /> {/* example of other top-level stuff */}
</React.Fragment>

可以获取 ThemeProvider 提供的主题

import { createGlobalStyle, ThemeProvider } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
    font-family: ${props => props.theme.fontFamily};
  }
`

// later in your app

<ThemeProvider theme={{ fontFamily: 'Helvetica Neue' }}>
  <React.Fragment>
    <Navigation /> {/* example of other top-level stuff */}
    <GlobalStyle whiteColor />
  </React.Fragment>
</ThemeProvider>

keyframes

添加动画

import styled, { keyframes } from 'styled-components'

const fadeIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`

const FadeInButton = styled.button`
  animation: 1s ${fadeIn} ease-out;
`

StyleSheetManager

修改或覆盖子组件样式、更改样式的渲染行为 的辅助组件

disableVendorPrefixes 重置组件样式

import styled, { StyleSheetManager } from 'styled-components'

const Box = styled.div`
  color: ${props => props.theme.color};
  display: flex;
`

render(
  <StyleSheetManager disableVendorPrefixes>
    <Box>If you inspect me, there are no vendor prefixes for the flexbox style.</Box>
  </StyleSheetManager>
)

在这里插入图片描述

stylisRTLPlugin 改变样式渲染方式 从右到左

import styled, { StyleSheetManager } from 'styled-components'
import stylisRTLPlugin from 'stylis-plugin-rtl';

const Box = styled.div`
  background: mediumseagreen;
  border-left: 10px solid red;
`

render(
  <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}>
    <Box>My border is now on the right!</Box>
  </StyleSheetManager>
)

在这里插入图片描述

isStyledComponent

用于判断组件是否被 styled 渲染过

import React from 'react'
import styled, { isStyledComponent } from 'styled-components'
import MaybeStyledComponent from './somewhere-else'

let TargetedComponent = isStyledComponent(MaybeStyledComponent)
  ? MaybeStyledComponent
  : styled(MaybeStyledComponent)``

const ParentComponent = styled.div`
  color: cornflowerblue;

  ${TargetedComponent} {
    color: tomato;
  }
`

withTheme

一个高阶函数,用于从 ThemeProvider 获取当前主题并将其作为props传递给包装的组件

import { withTheme } from 'styled-components'

class MyComponent extends React.Component {
  render() {
    console.log('Current theme: ', this.props.theme)
    // ...
  }
}

export default withTheme(MyComponent)

所有 styled 组件都会收到主题的props,因此仅当你有其它原因需要访问主题时才这样用

ThemeConsumer

ThemeProvider的配套组件,可以在渲染期间动态访问主题

import { ThemeConsumer } from 'styled-components'

export default class MyComponent extends React.Component {
  render() {
    return (
      <ThemeConsumer>
        {theme => <div>The theme color is {theme.color}.</div>}
      </ThemeConsumer>
    )
  }
}

所有 styled 组件都会收到主题的props,因此仅当你有其它原因需要访问主题时才这样用

支持的样式写法

& 是我们为该样式组件生成的唯一类名替换,从而可以易于拥有复杂的逻辑

const Example = styled.div`
  /* all declarations will be prefixed */
  padding: 2em 1em;
  background: papayawhip;

  /* pseudo selectors work as well */
  &:hover {
    background: palevioletred;
  }

  /* media queries are no problem */
  @media (max-width: 600px) {
    background: tomato;

    /* nested rules work as expected */
    &:hover {
      background: yellow;
    }
  }

  > p {
    /* descendant-selectors work as well, but are more of an escape hatch */
    text-decoration: underline;
  }

  /* Contextual selectors work as well */
  html.test & {
    display: none;
  }
`;

render(
  <Example>
    <p>Hello World!</p>
  </Example>
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

styled-components 的用法 的相关文章

随机推荐

  • 《影响力》-社会心理学入门书

    这本书评价如何 豆瓣评分8 6 大多数人认可度还是很高的 查理芒格 穷查理宝典 的作者 觉得作者在 影响力 主题上 远超其他科学家 因此赠送了一股伯克希尔的A级股票 据说价值22w美元 财富 杂志推荐75本商业必读之一 我个人觉得 这本书其
  • 使用R语言中的survival包进行生存分析是一种常见的统计方法

    使用R语言中的survival包进行生存分析是一种常见的统计方法 在生存分析中 我们经常需要创建一个生存对象来存储事件发生时间和事件状态 在本文中 我们将介绍如何使用survival包中的Surv函数来创建生存对象 并解读其结果 Surv函
  • 代码随想录算法训练营第十九天

    动态规划系列5 6 7 8 377 组合总和 未看解答自己编写的青春版 重点 代码随想录的代码 我的代码 当天晚上理解后自己编写 求排列数的题 用二维DP过不了 自己捋逻辑的话 也是可以觉得有漏洞 但是怎么修改 一下子还没思路 包括后面的
  • GPRS公网通讯

    GPRS应用中TCP IP PPP基本概念 的原理与此差不多 实际上GPRS DTU上实现的是协议栈是TCP IP Over PPP 我们在使用时必须要有一些相应的概念 因此在下面我们就与SARO 3130P使用相关的一些事项作一些简要的说
  • gerrit提交出现remote rejected change closed错误

    看了这边文章 原因就像提示信息所说3203已经关闭了 change id找不到了 分析了原因 我的问题是因为之前的一次提交 3203 anandoned掉了 所以找不到这个change id 将这次提交重新恢复后 push成功
  • 区块链技术实战学习路线图

    请大家前往深入浅出区块链主站 获取最新内容 本章的文章越来越多 本文是一个索引帖 方便找到自己感兴趣的文章 你也可以使用左侧的分类 标签及搜索功能 有新文章时会更新本文 建议大家加入收藏夹中 如果你觉得本站不错 欢迎你转发给朋友 引言 给迷
  • 编写简单的linux shell脚本

    1 touch hello sh 2 vi hello sh 键入i 插入 bin sh echo hello world 键入 esc wq 3 chmod 700 hello sh 4 执行 hello sh
  • linux 上生成图片的问题 (awt)

    1 启动xwindow 执行命令 xhost local 2 参考下面资料 原因 Linux无图形支持环境配置 解决 在catalina sh 中加入 Djava awt headless true 或者在 bash profile中增加
  • Redis持久化AOF

    目录 1 AOF简介 2 AOF持久化流程 3 AOF默认不开启 4 AOF和RDB同时开启 redis听谁的 5 AOF启动 修复 恢复 6 AOF同步频率设置 7 Rewrite压缩 7 1 是什么 7 2 重写原理 如何实现重写 8
  • 微信小程序:自动生成打卡海报

    文章目录 1 前言 2 界面展示 3 部分代码展示以及原理解释 4 结语 完整项目下载 下载链接 1 前言 在当前的背单词小程序开发中 为满足用户学习完成后的展示需求 计划引入自动生成打卡海报功能 以提升用户参与度与推广效果 除了基本的海报
  • Window XP驱动开发(十三) 芯片功能驱动端 (代码实现,针对USB2.0 芯片CY7C68013A)

    转载请标明是引用于 http blog csdn net chenyujing1234 欢迎大家提出意见 一起讨论 需要源码的可以与我联系 针对USB2 0 芯片CY7C68013A FPGA实现的高速传输应用来写XP下的USB驱动程序 说
  • 医学图像配准工具Elastix的配置和入门

    一 Elastix介绍 Elastix是一个基于ITK开发的处理医学图像配准问题的工具 Elastix提供了很方便的命令行使用方式以供使用者进行配准应用 同时Elastix是开源的 并且采用模块式构成 可以根据源代码进行开发 或者添加新的模
  • 在LinuxBridge/OVS中使用VxLAN组网以及创建VTEP

    原文来自于 https blog lofyer org E5 9C A8linux bridge ovs E4 B8 AD E4 BD BF E7 94 A8vxlan E7 BB 84 E7 BD 91 E4 BB A5 E5 8F 8A
  • 【满分】【华为OD机试真题2023 JS】箱子之形摆放

    华为OD机试真题 2023年度机试题库全覆盖 刷题指南点这里 箱子之形摆放 知识点数组 时间限制 1s 空间限制 128MB 限定语言 不限 题目描述 有一批箱子 形式为字符串 设为str 要求将这批箱子按从上到下以之形的顺序摆放在宽度为n
  • js的事件执行机制(Event loop)

    同步任务 执行主线程上排队执行的任务 只有前一个任务执行完毕 下一个任务才会开始执行 异步任务 不进入主线程 而进入 任务队列 task queue 的任务 只有 任务队列 通知主线程 某个异步任务可以执行了 该任务才会进入主线程执行 事件
  • docker安装nginx太多坑了,果断放弃

    以下是我本人的个人看法 如有不对可在评论区讨论交流 1 listen的端口受限于docker p的参数 一个nginx容器conf文件只能listen同一个端口 2 修改配置文件麻烦 还有docker exec进入到容器内部进行操作 当然
  • 医疗保健软件必备指南

    对许多人来说 软件可能是一种奢侈品 只会给生活在 21 世纪的人们带来一些额外好处 但有时 软件可能是救命稻草 起着生死攸关的作用 根据医疗行业的部分统计数据 我们清醒地发现 美国平均每年约有 25 万至 40 万患者死于本可预防的医疗差错
  • Qt队列的使用

    一 queue 队列 队列是一种先进先出的数据结构 是一个模板类 队列和栈是一种数据逻辑概念 即数据能进行的操作 主要区别是 队列先进先出 First In First Out 栈后进先出 链表和顺序表是一种数据存放方式 主要区别是 链表有
  • 向日葵远程连接Ubuntu出现 “连接中断“ 的解决方法

    向日葵远程连接Ubuntu出现 连接中断 的解决方法 https www cnblogs com wangling1820 p 13448397 html 方法一 参考博客1 https blog csdn net wzf20162016
  • styled-components 的用法

    用于给标签或组件添加样式 给标签或组件添加样式 import styled from styled components styled button 给button标签添加样式 const Button styled button back