reactjs - 使用 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;
解决方案
添加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)'};
}`
推荐阅读
- json - 如果键名与“名称”匹配,则使用 jq 提取键值
- java - 我正在做一个项目,我必须从一项活动中传输名称和值等数据
- angular - customize ng-bootstrap carousel?
- javascript - 使用 javascript 删除 div 后无法读取 null 错误的属性“appendChild”
- php - python中什么等价的“变量=>数组('值')”?
- javascript - Medium.com 风格的图像缩放
- c# - 如何将 GameLift 与 Unity3d 集成为游戏客户端
- javascript - React 中 setState 的这两种类型的更新函数是否相等?
- python - 在 SQLite 文件中拆分和清理推文
- javafx - 隐藏选项卡上的内容的 JavaFx 快照