样式化组件,输入元素上的反向选择器模式



我正在尝试遵循此处详述的"反向选择器"模式。以下两个都嵌套在 label 标记中。单击标签将激活输入,但不应用 FakeInput 中的条件样式。

有什么想法吗?

export const CheckboxInput = styled.input`
  position: absolute;
  opacity: 0;
`;
export const FakeInput = styled.div`
  height: 2.2rem;
  width: 2.2rem;
  margin-right: 1rem;
  border-radius: 0.2rem;
  background-color: #333;
  color: #333;
  font-size: 1.8rem;
  ${CheckboxInput}:checked & {
      background-color: green;
      color: white;
  }
`;

它从此函数呈现:

renderInputRow({ key, name }) {
    const inputRow = (
        <CheckboxLabel key={key}>{name}
            <CheckboxInput type="checkbox" name={key} />
            <FakeInput className="fa fa-check" />
        </CheckboxLabel>
    );
    return inputRow;
}

幸运的是,我们在网站上的示例没有任何问题,但是您的选择器在这里存在问题:

${CheckboxInput}:checked &

就其本身而言,这个选择器完全没问题,并表示"选中时 CheckboxInput 的任何子项",但您的代码包含以下内容:

<CheckboxInput type="checkbox" name={key} />
<FakeInput className="fa fa-check" />

所以你会想说"CheckboxInput的任何兄弟姐妹",这将是:

${CheckboxInput}:checked ~ &

我已经快速将您的代码粘贴到 CodeSandbox 中以确认它是否有效:https://codesandbox.io/s/rkmNRByE4

希望这对:)有所帮助

最新更新