如何使用 styled-components 切换 css 样式?

How to toggle css style using styled-components?

我创建了一个切换开关,可以从暗模式切换到亮模式。我正在尝试添加样式,这将在我单击切换时更改 svg 的 fill: ""path:first-child是上图标,path:last-child是下图标。

import { ReactComponent as ModeIcon} from '../../../assets/icons/mode-icon.svg';
import styled from 'styled-components';
import ThemeContext from "../../../store/themeContext";
import { useContext } from "react";

const Switcher = () => {
  const themeCtx = useContext(ThemeContext);
  const ToggleMode = () => {
    themeCtx.toggleMode()
  }
  return (
    <StyledSwitcher><ModeIcon onClick={ToggleMode}/></StyledSwitcher>
  )
}

export default Switcher;

const StyledSwitcher = styled.div`
svg{

  path:first-child{
    fill: #005FCE;
  }
  path:last-child{
    fill: #white;
  }
}
`;
import React, {useState} from 'react'
import { string } from 'yup';

type ContextObj = {
    toggleMode: any;
    theme: string;
  };

const ThemeContext = React.createContext<ContextObj>({
  toggleMode: () => {},
  theme: "dark",
  });

export const ThemeContextProvider = (props: any) => {
    const [theme, setTheme] = useState("dark");
  
    const themeToggler = ()=> {
      theme ==='light' ? setTheme('dark') : setTheme('light');
      console.log("Swiutch toggle")
    }

      const contextValue: ContextObj = {
        toggleMode: themeToggler,
        theme: theme,
  };
  return (
    <ThemeContext.Provider value={contextValue}>{props.children}</ThemeContext.Provider>
  )
};
export default ThemeContext

首先,您应该从上下文中向您的组件提供 'theme' 值(就像您对 toggleMode() 所做的那样)。然后你可以给你的StyledSwitcher添加'theme'class属性,例如:

const Switcher = () => {
  const themeCtx = useContext(ThemeContext);
  const ToggleMode = () => {
    themeCtx.toggleMode()
  }

  const themeValue = () => {
    themeCtx.theme()
  }
  return (
    <StyledSwitcher className={themeValue}><ModeIcon onClick={ToggleMode}/></StyledSwitcher>
  )
}

之后,将您设置样式的组件配置为与该附加组件一起使用 class:

const StyledSwitcher = styled.div`
  &.light{
    svg{
      path:first-child{ fill: #005FCE; }
      path:last-child{ fill: #white; }
    }
  }
  &.dark{
    svg{
      path:first-child{ fill: #white; }
      path:last-child{ fill: #005FCE; }
    }
  }
`;