styled-components 的用法

2023-10-17 17:30
文章标签 用法 components styled

本文主要是介绍styled-components 的用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

给标签或组件添加样式

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

<divcss={`background: papayawhip;color: ${props => props.theme.colors.text};`}
/><Buttoncss="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>
);

这篇关于styled-components 的用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/226873

相关文章

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

解读GC日志中的各项指标用法

《解读GC日志中的各项指标用法》:本文主要介绍GC日志中的各项指标用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、基础 GC 日志格式(以 G1 为例)1. Minor GC 日志2. Full GC 日志二、关键指标解析1. GC 类型与触发原因2. 堆

MySQL数据库中ENUM的用法是什么详解

《MySQL数据库中ENUM的用法是什么详解》ENUM是一个字符串对象,用于指定一组预定义的值,并可在创建表时使用,下面:本文主要介绍MySQL数据库中ENUM的用法是什么的相关资料,文中通过代码... 目录mysql 中 ENUM 的用法一、ENUM 的定义与语法二、ENUM 的特点三、ENUM 的用法1

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

MySQL之InnoDB存储引擎中的索引用法及说明

《MySQL之InnoDB存储引擎中的索引用法及说明》:本文主要介绍MySQL之InnoDB存储引擎中的索引用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录1、背景2、准备3、正篇【1】存储用户记录的数据页【2】存储目录项记录的数据页【3】聚簇索引【4】二

mysql中的数据目录用法及说明

《mysql中的数据目录用法及说明》:本文主要介绍mysql中的数据目录用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、版本3、数据目录4、总结1、背景安装mysql之后,在安装目录下会有一个data目录,我们创建的数据库、创建的表、插入的

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

Mysql中isnull,ifnull,nullif的用法及语义详解

《Mysql中isnull,ifnull,nullif的用法及语义详解》MySQL中ISNULL判断表达式是否为NULL,IFNULL替换NULL值为指定值,NULLIF在表达式相等时返回NULL,用... 目录mysql中isnull,ifnull,nullif的用法1. ISNULL(expr) → 判

Java中的for循环高级用法

《Java中的for循环高级用法》本文系统解析Java中传统、增强型for循环、StreamAPI及并行流的实现原理与性能差异,并通过大量代码示例展示实际开发中的最佳实践,感兴趣的朋友一起看看吧... 目录前言一、基础篇:传统for循环1.1 标准语法结构1.2 典型应用场景二、进阶篇:增强型for循环2.

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编