【问题标题】:implementing dark mode with Themeprovider and styled components使用 Themeprovider 和样式化组件实现暗模式
【发布时间】:2020-10-23 18:20:17
【问题描述】:

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

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

【问题讨论】:

  • 大声笑我也有同样的问题,你知道了吗?

标签: reactjs styled-components


【解决方案1】:

在此代码中添加lightTheme={isLight}

在:&lt;ToggleContainer onClick={toggleTheme} &gt;

决赛:&lt;ToggleContainer onClick={toggleTheme} lightTheme={isLight}&gt;

另外,你可以使用下面的变换来切换,

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

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

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2018-04-01
    • 2023-02-07
    • 1970-01-01
    • 2021-01-23
    • 2021-06-09
    • 2020-09-26
    • 2020-09-22
    • 2020-03-26
    相关资源
    最近更新 更多