初识style-components
Styled-components 是一个用于在 React 中编写 CSS 的库,它允许你通过 JavaScript 将样式与组件结合起来,本质上还是组件化开发,将你定义的样式组件包裹在你需要修改样式的标签或文本上,样式组件将转换为一个实际的dom去包裹住你的标签或文本,从而起到修改样式的作用
1. 安装
首先,在你的项目中安装 Styled-components
npm install styled-components # 或 yarn add styled-components
复制
2. 使用方式
2.1. 组件内使用不推荐
import styled from 'styled-components'; const Button = styled.button` background: palevioletred; border-radius: 3px; border: none; color: white; padding: 0.5em 1em; cursor: pointer; `; const App = () => ( <Button>Click Me</Button> ); export default App;
复制
2.2. 组件外部使用推荐
定义一个.ts文件用于书写样式,并导出
import styled from 'styled-components' export const LoginDiv = styled.div` margin: 100px auto; width: 500px; height: 400px; border: 1px solid; border-radius: 8px; `
复制
组件中导入外部样式使用
import React from 'react'; import { LoginDiv } from './index'; const Login = () => { return ( <LoginDiv> <div>div</div> </LoginDiv> ) } export default Login
复制
基本用法
为了方便阅读,下面的案例全部采用了使用方式中 2.1 中的写法,但这种写法不建议在开发中使用,实际开发中建议使用 2.2 中推荐的写法
1. 简单使用
import styled from 'styled-components'; // 定义基本样式 // 注意:这里的styled.button,就是让页面渲染之后,将它变成一个button html标签 // 类比推理,你还可以指定其他的。例如styled.div、styled.span、styled.h1等 const Button = styled.button` background: palevioletred; border-radius: 3px; border: none; color: white; padding: 0.5em 1em; cursor: pointer; `; // 给样式增加hover效果 const Button = styled.button` background: palevioletred; border-radius: 3px; border: none; color: white; padding: 0.5em 1em; cursor: pointer; &:hover { background: darkviolet; } `;
复制
2. 使用嵌套样式
CSS 样式可以嵌套,就像在 SASS 中一样:
import styled from 'styled-components'; const Container = styled.div` padding: 2em; background: papayawhip; .title { color: palevioletred; font-size: 2em; } .content { color: darkslategray; } `; const App = () => ( <Container> <div className="title">Title</div> <div cl
复制