styled-components快速使用教程

styled-components快速使用教程styled components 是一个非常流行的 CSS in JS 库 它允许你以声明式的方式编写样式 并且可以将这些样式直接与你的 React 组件关联起来

大家好,欢迎来到IT知识分享网。

styled-components 是一个非常流行的 CSS-in-JS 库,它允许你以声明式的方式编写样式,并且可以将这些样式直接与你的 React 组件关联起来。

styled-components快速使用教程

安装

# 使用 npm 安装 npm install styled-components # 使用yarn 安装 yarn add styled-components # 使用 pnpm 安装 pnpm add styled-components

创建基本样式组件

在你的组件文件中引入 styled-components 并创建一个新的样式化的组件:

import React from 'react'; import styled from 'styled-components'; const Button = styled.button` background-color: blue; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; &:hover { opacity: 0.8; } `; function App() { return ( <div> <Button>Click me!</Button> </div> ); } export default App;

使用属性动态更改样式

import React from 'react'; import styled from 'styled-components'; const Box = styled.div` width: ${props => props.width}px; height: ${props => props.height}px; background-color: ${props => props.bgColor}; `; function App() { return ( <Box width={200} height={200} bgColor="red" /> ); } export default App;

样式继承

import React from 'react'; import styled from 'styled-components'; const BaseButton = styled.button` font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; const BlueButton = styled(BaseButton)` color: white; background-color: blue; `; function App() { return ( <BlueButton>Blue Button</BlueButton> ); } export default App;

样式复用

import React from 'react'; import styled, { css } from 'styled-components'; const buttonStyles = css` font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; const Button = styled.button` ${buttonStyles} `; const SubmitButton = styled(Button)` background: palevioletred; color: white; `; function App() { return ( <SubmitButton type="submit">Submit</SubmitButton> ); } export default App;

全局样式

import React from 'react'; import { createGlobalStyle } from 'styled-components'; const GlobalStyle = createGlobalStyle` body { background: papayawhip; } `; function App() { return ( <> <GlobalStyle /> {/* Your app components */} </> ); } export default App;

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/145440.html

(0)
上一篇 2025-04-20 16:33
下一篇 2025-04-20 16:45

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信