You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击input标签时反转两个React LangText组件文本颜色的实现求教

解决方案

你之前的方案不生效是因为styled-components会在编译阶段把JS变量的值嵌入生成的CSS代码中,运行时修改顶层JS变量不会触发样式更新,我们可以直接利用CSS的相邻兄弟选择器+后代选择器,通过input的checked状态联动控制两个文本的颜色,不需要修改组件逻辑,完全使用styled-components内嵌样式实现。

修改后的样式文件代码

import styled from "styled-components";

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;
        }
        /* 勾选状态下反转颜色:ENG变黑色,EST变白色 */
        p:nth-child(1) {
            color: #000;
        }
        p:nth-child(2) {
            color: #fff;
        }
    }
`

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;

  &:before {
      content: "";
      position: absolute;
      top: 15px;
      left: 2px;
      width: 50px;
      height: 20px;
      border-radius: 45px;
      transition: 0.2s;
      background: #000;
      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;
    /* 初始状态:ENG白色,EST黑色 */
    &:nth-child(1) {
        color: #fff;
    }
    &:nth-child(2) {
        color: #000;
    }
`;

实现逻辑

  • 初始状态直接在LangText组件中通过nth-child选择器分别设置两个文本的默认颜色,ENG为白色、EST为黑色
  • 利用Input的checked伪类,通过相邻兄弟选择器选中后续的Slider节点,再通过后代选择器修改两个LangText的颜色,实现点击切换时颜色反转
  • 无需修改原有的组件逻辑代码,也不需要额外引入React状态管理,完全符合styled-components内嵌样式的开发习惯

内容的提问来源于stack exchange,提问作者Taavi Raudkivi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:36:02