Skip to main content

Styled Components 的使用

· 2 min read
Lex
Front End Engineer @ Baoxiaohe

CSS-in-JS

模板字符串#

模板字符串是 ES6 新增的语法,对字符串的拼接很便捷。

let temp = "React";console.log(`Hello ${temp}`);

再来看一种更酷的写法 👇

let name = "Kobe";let nikename = "黑曼巴";
function test(...args) {  console.log(args);}
test(name, nikename); // (2) ["Kobe", "黑曼巴"]
// (3) [Array(3), "Kobe", "黑曼巴"]// (3) ["My name is ", ",people call me ", "!", raw: Array(3)]test`My name is ${name},people call me ${nikename}!`;

是的,如你所见,可以通过模板字符串的方式对一个函数进行调用,这被称为标签模板字符串

styled components#

styled components库就运用了标签模板字符串的语法 👀

import React, { PureComponent } from "react";import styled from "styled-components";
const Wrapper = styled.div`  font-size: 30px;  color: red;`;
export default class App extends PureComponent {  render() {    return <Wrapper>Hello styled-components</Wrapper>;  }}

props 穿透#

//输入框将变成password类型 、//给样式组件 Wrapper 设置属性会穿透到模板字符串内const Wrapper = styled.input`  background-color: pink`;
export default class App extends PureComponent {  render() {    return <Wrapper type="password">;  }}

如果你觉得在样式组件添加样式显得很不优雅,也可以这样做

const Wrapper = styled.input.attrs({  type: "passwords",})`  font-size: 14px;`;

使用 attrs#

好的,attrs 函数返回一个 function,重要的是可以使用 arrts 设置动态样式,具体是传入 state 作为 props 属性 👇

// state 改变,样式也会更新const Wrapper = styled.input.arrts({  input: "text",})`  color: ${props => props.color}`;
export default class App extends PureComponent {  constructor() {    super()    this.state= {      color: "red"    }  }
  render() {    return <Wrapper color={this.state.color}>;  }}

这就是 styled components 中 State-based styling 的解决方案,不同于 Vue 中的动态 class

// 直接内联样式或者class= "['normal', isActive ? 'active' : '']"

继承#

继承组件的样式也很简单

const Wrapper = styled(样式组件名)`  background-color: pink;`;

设置主题#

Maybe use css-variables is better in most sence.

import React, { PureComponent } from "react";import styled, { ThemeProvider } from "styled-components";
const Home = styled.div`  color: ${(props) => props.theme.themeColor};  font-size: ${(props) => props.theme.fontSize};`;
export default class App extends PureComponent {  render() {    return (      // 主题样式      <ThemeProvider theme={{ themeColor: "red", fontSize: "30px" }}>        {/* 样式组件名 */}        <Home />      </ThemeProvider>    );  }}

That's all👏

参考