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

如何将含+相邻选择器的传统CSS转换为React styled-components写法

正确实现方式

你需要把这条规则写在 Input 组件的样式定义内,通过 ${} 语法引用已定义的 Icon 组件即可,完整代码如下:

const Input = styled.input`
  font-family: Poppins-Medium;
  font-size: 16px;
  color: #333333;
  line-height: 1.2;
  display: block;
  width: 100%;
  height: 55px;
  background: transparent;
  padding: 0 7px 0 43px;
  border: none;
  outline: none;
  margin: 0;

  /* 新增的聚焦相邻选择器规则 */
  &:focus + ${Icon}::after {
    color: #a64bf4;
  }
`;

const Icon = styled.span`
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  &:after {
    content: attr(data-symbol);
    font-family: Material-Design-Iconic-Font;
    color: #adadad;
    font-size: 22px;
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    height: calc(100% - 20px);
    bottom: 0;
    left: 0;
    padding-left: 13px;
    padding-top: 3px;
  }
  &:before {
    content: "";
    display: block;
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 0;
    height: 2px;
    background: #7f7f7f;
    -webkit-transition: all 0.4s;
    -o-transition: all 0.4s;
    -moz-transition: all 0.4s;
    transition: all 0.4s;
  }
`;

原理解释

styled-components 支持直接在样式模板中通过 ${组件名} 的方式引用其他 styled 组件,会自动替换为该组件对应的生成类名,最终渲染出来的CSS和你原生的写法完全等价。
你之前的写法错误点有两个:

  • 没有用 ${} 包裹引用的 Icon 组件,无法被正确解析为对应类名
  • 这条规则的触发主体是Input的聚焦状态,所以需要写在Input的样式定义里,而不是Icon的样式定义内

注意要保证DOM结构中 Input 组件的下一个相邻元素就是 Icon 组件,中间不能插入其他节点,否则相邻选择器 + 不会生效。


内容的提问来源于stack exchange,提问作者Johnatan De Leon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:06:03