Reactjs样式化组件无法正常工作

时间:2020-09-18 19:55:16

标签: css reactjs styled-components

我有一个样式复选框,我想将checked:false的背景设置为白色,而checked:true的背景设置为绿色

但是问题是背景颜色始终保持绿色,我不知道为什么。

我正在使用此复选框组件的react组件运行正常,它只是我无法调整的背景颜色

有什么建议吗?

    const CheckboxContainer = styled.div`
  display: inline-block;
  vertical-align: middle;
`

const Icon = styled.svg`
  fill: none;
  stroke: white;
  stroke-width: 2px;
`

const HiddenCheckbox = styled.input.attrs({ type: 'checkbox' })`
  border: 0;
  clip: rect(0 0 0 0);
  clippath: inset(50%);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  white-space: nowrap;
  width: 1px;
`

const StyledCheckbox = styled.div`
  display: inline-block;
  width: 16px;
  height: 16px;
  background: #ffffff;
  border-radius: 3px;
  transition: all 150ms;
  margin-top: 10px;

  ${HiddenCheckbox}:focus + & {
    background: ${({ checked }) => (checked ? '#06ba63' : '#ffffff')};
  }

  ${Icon} {
    visibility: ${({ checked }) => (checked ? 'visible' : 'hidden')};
  }
`

const Checkbox = ({ className, checked, ...props }) => (
  <CheckboxContainer className={className}>
    <HiddenCheckbox checked={checked} {...props} />
    <StyledCheckbox checked={checked}>
      <Icon viewBox="0 0 24 24">
        <polyline points="20 6 9 17 4 12" />
      </Icon>
    </StyledCheckbox>
  </CheckboxContainer>
)

export default Checkbox

2 个答案:

答案 0 :(得分:1)

您应检查复选框中的checked而不是focus

${HiddenCheckbox}:checked + & {
    background: ${({ checked }) => (checked ? '#06ba63' : '#ffffff')};
  }

答案 1 :(得分:0)

如果HiddenStyled复选框都从checked获得相同的值,则只需要使用传递给checked的{​​{1}}的值(就像您使用Icon一样):

StyledCheckbox

另一种选择是仅在通过CSS选择器选中const StyledCheckbox = styled.div` display: inline-block; width: 16px; height: 16px; background: #ffffff; border-radius: 3px; transition: all 150ms; margin-top: 10px; background: ${({ checked }) => (checked ? '#06ba63' : '#ffffff')}; ${Icon} { visibility: ${({ checked }) => (checked ? 'visible' : 'hidden')}; } ` 时应用样式:

HiddenCheckbox