场景

在一些前端开发场景中,一套界面风格是无法满足业务需求的。
当遇到需要切换主题风格的需求时,就需要能不同样式能够无缝切换。
下面介绍一个适用于 React 的库,以及如何切换风格如德芙般丝滑。

styled-components

官网地址: https://styled-components.com/
Github: https://github.com/styled-components

demo

talk is cheap, show you the code.
下面是我写的一个例子,演示如何使用 styled-components 切换风格。

import "./styles.css";
import styled from "styled-components";
import { ThemeProvider } from "styled-components";
import { useState } from "react";

// 定义一个按钮组件,样式中 color 值受控于 props
const Button = styled.button`
  color: ${(props) => props.theme.color};
  border: 2px solid ${(props) => props.theme.color};
  background: ${(props) => props.theme.bg};
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;
  cursor: pointer;
`;

// 皮肤1,绿色按钮
const greenButton = {
  color: "green",
  bg: "white"
};

// 皮肤2,红色按钮
const redButton = {
  color: "red",
  bg: "white"
};

export default function App() {
  // 个人习惯使用 React Hooks 的方式,定义一个 state
  const [isRed, setIsRed] = useState(false);

  // 处理颜色转变,非红即绿,非绿即红
  const changeColor = () => {
    setIsRed(!isRed);
  };

  return (
    // 根据 theme 渲染对应的皮肤
    <ThemeProvider theme={isRed === true ? redButton : greenButton}>
      <div className="App">
        <Button onClick={changeColor}>点我变色</Button>
      </div>
    </ThemeProvider>
  );
}

当我们点击按钮时,按钮风格会切换为另一套。

点击前
https://lookcos.cn/usr/uploads/2022/10/3557034076.png
点击后
https://lookcos.cn/usr/uploads/2022/10/1527878301.png

SandBox演示:
https://codesandbox.io/s/elated-bose-hw01e5?file=/src/App.js

添加新评论