单击输入标记时,反转两种React组件文本颜色



我是React的新手,没有找到这个简单问题的任何解决方案。

当点击切换按钮时,我想恢复LangText的颜色-最初ENG是白色,EST是黑色,每次点击输入时,颜色都会反转。

我有单独的文件用于返回和设置组件样式。

我试图更改样式组件标记内的变量(位于样式组件文件顶部(的颜色,因此使用CSS-interInput伪类&:选中+span。看起来超现实,但无论如何都不起作用。

我将非常感谢一个如何在这种情况下同时改变两种颜色的例子。组件的例子总是太少了,通常CSS是单独使用的,但对我来说,这种方法更可读、更合乎逻辑。

import React from 'react'
import { Input, InputWrapper, Slider, ToggleContainer, LangText} from './LangugageToggleElements';
const LanguageToggle = ({onChange}) =>  {

return(
<ToggleContainer>
<InputWrapper>
<Input type="checkbox" onChange={onChange}/>
<Slider>
<LangText>ENG</LangText>
<LangText>EST</LangText>
</Slider>
</InputWrapper>
</ToggleContainer>
)} ;

export default LanguageToggle

import styled from "styled-components";
let toggleBackground = "#000";
let textColor = "#fff";
export const ToggleContainer = styled.div`
position: absolute;
top: 10px;
right: 20px;
`
export const InputWrapper = styled.label`
position: relative;
display: flex;
justify-content: center;
text-align: center;
`
export const Input = styled.input`
position: absolute;
left: -9999px;
top: -9999px;
&:checked + span {
&:before {
left: 52px;
}
}
`
export const Slider = styled.span`
display: flex;
justify-content: center;
text-align: center;
cursor: pointer;
width: 105px;
border-radius: 100px;
position: relative;
transition: background-color 0.2s;
color: ${textColor};
&:before {
content: "";
position: absolute;
top: 15px;
left: 2px;
width: 50px;
height: 20px;
border-radius: 45px;
transition: 0.2s;
background: ${toggleBackground};
box-shadow: 0 2px 4px 0 rgba(0, 35, 11, 0.2);
}
`;
export const LangText = styled.p`
padding-right: 5px;
padding-left: 5px;
z-index: 1;
letter-spacing: 3px;
`;

我认为您可以简单地使用useState钩子来维护复选框,并将其用于LangText。

<ToggleContainer>
<InputWrapper>
<Input type="checkbox" onChange={()=>{
onChange();
//use state hook to maitain the checkbox value
}}/>
<Slider>
<LangText className={isChecboxValue === x ? color : invert }>ENG</LangText>
<LangText className={isChecboxValue === y ? invert: color}>EST</LangText>
</Slider>
</InputWrapper>
</ToggleContainer>

相关内容

最新更新