首页 > 解决方案 > 使用 Themeprovider 和样式化组件实现暗模式

问题描述

我对样式组件了解不多,我正在使用切换开关来更改主题,并且我的主题确实从暗切换到亮,但我使用的图标不会切换图标。图标是有效的,当我切换组件的顺序时,月亮图标只显示,我猜这是有语法的东西?

import React from 'react'
import { func, string } from 'prop-types';
import styled from 'styled-components';
import { ReactComponent as MoonIcon } from '../components/icons/moon.svg';
import { ReactComponent as SunIcon } from '../components/icons/sun.svg';

const ToggleContainer = styled.button`
  background: ${({ theme }) => theme.gradient};
  border: 2px solid ${({ theme }) => theme.toggleBorder};
  border-radius: 30px;
  cursor: pointer;
  display: flex;
  font-size: 0.5rem;
  justify-content: space-between;
  margin: 0 auto;
  overflow: hidden;
  padding: 0.5rem;
  position: relative;
  width: 8rem;
  height: 4rem;

  svg {
    height: auto;
    width: 2.5rem;
    transition: all 0.3s linear;
    
    // sun icon
    &:first-child {
      transform: ${({ lightTheme }) => lightTheme ? 'translateY(0)' : 'translateY(100px)'};
    }
    
    // moon icon
    &:nth-child(2) {
      transform: ${({ lightTheme }) => lightTheme ? 'translateY(-100px)' : 'translateY(0)'};
    }
  }
`;
const Toggle = ({ theme, toggleTheme }) => {
    
  const isLight = theme === 'light';
  return (
    <ToggleContainer onClick={toggleTheme} >
      <MoonIcon />
      <SunIcon />
    </ToggleContainer>
  );
};

Toggle.propTypes = {
  theme: string.isRequired,
  toggleTheme: func.isRequired,
}

export default Toggle;

灯光模式

暗模式

标签: reactjsstyled-components

解决方案


添加lightTheme={isLight}到此代码

在:<ToggleContainer onClick={toggleTheme} >

最后:<ToggleContainer onClick={toggleTheme} lightTheme={isLight}>

此外,您可以使用下面的变换进行切换,

`&:first-child {
  transform: ${({ lightTheme }) => lightTheme ? 'translateX(0px)' : 'translateX(-150px)'};
}    

&:nth-child(2) {
  transform: ${({ lightTheme }) => lightTheme ? 'translateX(100px)' : 'translateX(0px)'};
}`

推荐阅读