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 的用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/weixin_44240581/article/details/121585638
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/226873

相关文章

git stash命令基本用法详解

《gitstash命令基本用法详解》gitstash是Git中一个非常有用的命令,它可以临时保存当前工作区的修改,让你可以切换到其他分支或者处理其他任务,而不需要提交这些还未完成的修改,这篇文章主要... 目录一、基本用法1. 保存当前修改(包括暂存区和工作区的内容)2. 查看保存了哪些 stash3. 恢

Python struct.unpack() 用法及常见错误详解

《Pythonstruct.unpack()用法及常见错误详解》struct.unpack()是Python中用于将二进制数据(字节序列)解析为Python数据类型的函数,通常与struct.pa... 目录一、函数语法二、格式字符串详解三、使用示例示例 1:解析整数和浮点数示例 2:解析字符串示例 3:解

C++/类与对象/默认成员函数@构造函数的用法

《C++/类与对象/默认成员函数@构造函数的用法》:本文主要介绍C++/类与对象/默认成员函数@构造函数的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录名词概念默认成员函数构造函数概念函数特征显示构造函数隐式构造函数总结名词概念默认构造函数:不用传参就可以

javascript fetch 用法讲解

《javascriptfetch用法讲解》fetch是一个现代化的JavaScriptAPI,用于发送网络请求并获取资源,它是浏览器提供的全局方法,可以替代传统的XMLHttpRequest,这篇... 目录1. 基本语法1.1 语法1.2 示例:简单 GET 请求2. Response 对象3. 配置请求

Go 语言中的 Struct Tag 的用法详解

《Go语言中的StructTag的用法详解》在Go语言中,结构体字段标签(StructTag)是一种用于给字段添加元信息(metadata)的机制,常用于序列化(如JSON、XML)、ORM映... 目录一、结构体标签的基本语法二、json:"token"的具体含义三、常见的标签格式变体四、使用示例五、使用

mysql中的group by高级用法详解

《mysql中的groupby高级用法详解》MySQL中的GROUPBY是数据聚合分析的核心功能,主要用于将结果集按指定列分组,并结合聚合函数进行统计计算,本文给大家介绍mysql中的groupby... 目录一、基本语法与核心功能二、基础用法示例1. 单列分组统计2. 多列组合分组3. 与WHERE结合使

MySQL 字符串截取函数及用法详解

《MySQL字符串截取函数及用法详解》在MySQL中,字符串截取是常见的操作,主要用于从字符串中提取特定部分,MySQL提供了多种函数来实现这一功能,包括LEFT()、RIGHT()、SUBST... 目录mysql 字符串截取函数详解RIGHT(str, length):从右侧截取指定长度的字符SUBST

SQL Server中的PIVOT与UNPIVOT用法具体示例详解

《SQLServer中的PIVOT与UNPIVOT用法具体示例详解》这篇文章主要给大家介绍了关于SQLServer中的PIVOT与UNPIVOT用法的具体示例,SQLServer中PIVOT和U... 目录引言一、PIVOT:将行转换为列核心作用语法结构实战示例二、UNPIVOT:将列编程转换为行核心作用语

Java中 instanceof 的用法详细介绍

《Java中instanceof的用法详细介绍》在Java中,instanceof是一个二元运算符(类型比较操作符),用于检查一个对象是否是某个特定类、接口的实例,或者是否是其子类的实例,这篇文章... 目录引言基本语法基本作用1. 检查对象是否是指定类的实例2. 检查对象是否是子类的实例3. 检查对象是否

Java中的内部类和常用类用法解读

《Java中的内部类和常用类用法解读》:本文主要介绍Java中的内部类和常用类用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录内部类和常用类内部类成员内部类静态内部类局部内部类匿名内部类常用类Object类包装类String类StringBuffer和Stri