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

Styled components, reverse selector pattern on input elements

我正在尝试遵循详细 here 的 'Reverse Selector' 模式。以下两个都嵌套在 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 &

这个选择器本身完全没问题,表示 "any children of CheckboxInput when it's checked",但您的代码包含:

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

所以您要说 "any sibling of CheckboxInput",即:

${CheckboxInput}:checked ~ &

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

希望这对您有所帮助:)