【问题标题】:Styled components select previous sibling样式化的组件选择上一个兄弟
【发布时间】:2021-02-04 20:11:52
【问题描述】:

我正在构建一个表单,并尝试在输入聚焦后更改标签的颜色。 我正在使用样式化组件参考 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;
  }
`;

有没有办法做到不必改变标记的顺序?从标记的角度来看,在标签之前输入是违反直觉的。

谢谢。

【问题讨论】:

    标签: reactjs styled-components css-in-js


    【解决方案1】:

    首先你需要把输入放在标签之前。您可以使用 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;
      }
      
    `;
    

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2011-01-09
      • 2013-08-31
      • 1970-01-01
      相关资源
      最近更新 更多