【问题标题】:Invert two React component text colors when clicking on input tag单击输入标签时反转两种 React 组件文本颜色
【发布时间】:2021-12-19 00:40:43
【问题描述】:

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

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

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

我试图更改样式组件标签内的变量(位于样式组件文件顶部)的颜色,因此使用 CSS - Input 伪类 &:检查+跨度。看起来超现实,没有任何作用。

我会非常感谢一个如何同时更改两种颜色的示例,在这种情况下是时间。组件的例子总是太少,通常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;
`;

【问题讨论】:

  • 能否提供一个使用 jsFiddle 或 Codepen 的简化示例?

标签: javascript reactjs styled-components


【解决方案1】:

我认为您可以简单地使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-25
    • 2012-11-27
    • 2020-08-26
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2017-07-21
    相关资源
    最近更新 更多