首页 > 解决方案 > 样式化的组件选择上一个兄弟

问题描述

我正在构建一个表单,并且在输入聚焦后尝试更改标签的颜色。我正在使用样式化组件参考 api,如果我将标记作为输入后跟标签,我会发现它可以工作,这不是我的情况。我的标记是

<FieldWrapper>
  <StyledLabel htmlFor={id && id}>{label}</StyledLabel>
  <StyledInput
    type={type}
    id={id && id}
    autoComplete={autoComplete}
    {...rest}
  />
</FieldWrapper>

我的样式组件文件是这样的:

const FieldWrapper = styled.div`
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  position:relative;
  & ${StyledInput}:focus + ${StyledLabel} {
   color: red;
  }
`;

有没有办法实现不必改变标记的顺序?从标记的角度来看,在标签之前输入有悖常理。

谢谢。

标签: reactjsstyled-componentscss-in-js

解决方案


首先,您需要在标签之前输入输入。您可以使用 flex-direction:row-reverse; 在输入前显示标签。然后,不要使用引用变量 ${StyledLabel},只需使用输入和标签,如下例所示:

<FieldWrapper>
  <StyledInput
    type={type}
    id={id && id}
    autoComplete={autoComplete}
    {...rest}
  />
  <StyledLabel htmlFor={id && id}>{label}</StyledLabel>
  
</FieldWrapper>

然后在样式中:

const FieldWrapper = styled.div`

  display: flex;
  flex-wrap: wrap;
  flex-direction: row-reverse;
  width: 100%;
  position:relative;

  input:focus ~ label{
    color: green;
  }
  
`;

推荐阅读