在使用 React-hook-form 进行验证的情况下,标签转换不起作用

Label transition is not working in case of validations with React-hook-form

我正在尝试应用一种样式,当输入处于焦点时将标签移动到顶部。 在我尝试添加验证之前它运行良好。 示例代码:-

 <form onSubmit={handleSubmit(onSubmit)}>
    <div className="form__group">
      <input
        className="form__input"
        type="text"
        id="name"
        name="name"
        placeholder=" "
        ref={register}
      />
      {errors.name && <p className="error">{errors.name.message}</p>}
      <label className="form__label" htmlFor="name">
        Name
      </label>
    </div>
    <input type="submit" />
  </form>

提到的样式是:-

    .form__label {
    position: absolute;
    color: #777777;
    transition: all 0.3s;
    cursor: text;
    top: 16%;
    left: 6.5%;
  }
  
  form__input {
    &:focus {
      border: 2px solid blue;
      & + .form__label {
        top: 3px;
        left: 10px;
        color: blue;
      }
    }
    
    &:not(:placeholder-shown) + .form__label {
      top: 3px;
      left: 10px;
      color: blue;
    
    }
  }

上述问题的沙箱是here

问题是在上述情况下选择的是直接同级而不是“+”组合符,应该使用“~”组合符。

  • "+" 组合器选择直接兄弟,在没有错误的情况下是标签。所以它在开始时有效,但在其他情况下失败。
  • “~”组合器选择在所有情况下都有效的通用兄弟。

如果出现错误,标签不是导致问题的直接兄弟。