使用Themeprovider和样式化组件实现暗模式

时间:2020-07-03 04:10:53

标签: reactjs styled-components

我对样式化组件了解不多,我使用切换开关来更改主题,并且主题的确从暗到亮切换,但我使用的图标却不切换图标。这些图标是有效的,当我切换组件的顺序时,仅显示月亮图标,我猜这是语法问题吗?

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;

lightmode

darkmode

1 个答案:

答案 0 :(得分:0)

在此代码中添加 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)'};
}`