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版本切换工具pyenv的安装及用法

《python版本切换工具pyenv的安装及用法》Pyenv是管理Python版本的最佳工具之一,特别适合开发者和需要切换多个Python版本的用户,:本文主要介绍python版本切换工具pyen... 目录Pyenv 是什么?安装 Pyenv(MACOS)使用 Homebrew:配置 shell(zsh

Java中的CompletableFuture核心用法和常见场景

《Java中的CompletableFuture核心用法和常见场景》CompletableFuture是Java8引入的强大的异步编程工具,支持链式异步编程、组合、异常处理和回调,介绍其核心用法,通过... 目录1、引言2. 基本概念3. 创建 CompletableFuture3.1. 手动创建3.2.

MySQL中between and的基本用法、范围查询示例详解

《MySQL中betweenand的基本用法、范围查询示例详解》BETWEENAND操作符在MySQL中用于选择在两个值之间的数据,包括边界值,它支持数值和日期类型,示例展示了如何使用BETWEEN... 目录一、between and语法二、使用示例2.1、betwphpeen and数值查询2.2、be

Java序列化之serialVersionUID的用法解读

《Java序列化之serialVersionUID的用法解读》Java序列化之serialVersionUID:本文介绍了Java对象的序列化和反序列化过程,强调了serialVersionUID的作... 目录JavChina编程a序列化之serialVersionUID什么是序列化为什么要序列化serialV

python3中正则表达式处理函数用法总结

《python3中正则表达式处理函数用法总结》Python中的正则表达式是一个强大的文本处理工具,用于匹配、查找、替换等操作,在Python中正则表达式的操作主要通过内置的re模块来实现,这篇文章主要... 目录前言re.match函数re.search方法re.match 与 re.search的区别检索

MySQL 中的 JSON_CONTAIN用法示例详解

《MySQL中的JSON_CONTAIN用法示例详解》JSON_CONTAINS函数用于检查一个JSON文档中是否包含另一个JSON文档,这篇文章给大家介绍JSON_CONTAINS的用法、语法、... 目录深入了解 mysql 中的 jsON_CONTAINS1. JSON_CONTAINS 函数的概述2

JDK21对虚拟线程的几种用法实践指南

《JDK21对虚拟线程的几种用法实践指南》虚拟线程是Java中的一种轻量级线程,由JVM管理,特别适合于I/O密集型任务,:本文主要介绍JDK21对虚拟线程的几种用法,文中通过代码介绍的非常详细,... 目录一、参考官方文档二、什么是虚拟线程三、几种用法1、Thread.ofVirtual().start(

Java8 Collectors.toMap() 的两种用法

《Java8Collectors.toMap()的两种用法》Collectors.toMap():JDK8中提供,用于将Stream流转换为Map,本文给大家介绍Java8Collector... 目录一、简单介绍用法1:根据某一属性,对对象的实例或属性做映射用法2:根据某一属性,对对象集合进行去重二、Du

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数

Python中的sort方法、sorted函数与lambda表达式及用法详解

《Python中的sort方法、sorted函数与lambda表达式及用法详解》文章对比了Python中list.sort()与sorted()函数的区别,指出sort()原地排序返回None,sor... 目录1. sort()方法1.1 sort()方法1.2 基本语法和参数A. reverse参数B.