首页 > 解决方案 > 当您不能使用名称属性时,如何允许对单选按钮进行分组?

问题描述

我有一个自定义单选按钮组件,我想以某种方式对它们进行分组。选择一个取消选择另一个我必须检测一个的选择并取消选择另一个,所以问题是我在哪里这样做?它必须在某个地方完成,但机械师总是一样的。有什么建议吗?

这是我的组件的样子:

const StyledRadio = styled.div<RadioProps>`
  display: flex;
  background: ${(p) =>
    !p.checked
      ? "transparent"
      : "radial-gradient(#34515E 0%, #34515E 50%, transparent 50%, transparent)"};
  border-radius: 50%;
  border:        ${(p) => `2px solid ${theme.color.secondary}`};
  height:        ${(p) => `${radioSizes[p.size]}px`};
  margin-right:  5px;
  opacity:       ${(p) => (p.disabled ? 0.5 : 1)};
  width:         ${(p) => `${radioSizes[p.size]}px`};
  &:hover {
    cursor: pointer;
    background: radial-gradient(
      circle,
      #34515e 0%,
      #34515e 50%,
      transparent 50%,
      transparent
    );
    transform: scale (1.02);
    display: block;
  }
  &:active {
    transform: scale(1.1);
  }
`;

const RadioLabel = styled.label<{ size: string }>`
  color:          ${theme.color.secondary};
  cursor:         pointer;
  display:        flex;
  flex-direction: row-reverse;
  font-size:      ${theme.font.size.small};
`;

type RadioProps = {
  checked?:  boolean;
  children?: any;
  disabled?: boolean;
  label?:    string;
  onClick?:  (value?: any) => void;
  size?:     RadioSize;
  value?:    any;
};

export const Radio: FC<RadioProps> = ({
  disabled = false,
  onClick,
  children,
  checked,
  label = "",
  value,
  size = "small",
  ...rest
}) => {


  return (
    <RadioGroup
      disabled = {!!disabled}
      onClick  = {() => (!disabled && onClick ? onClick(value) : null)}
    >
      <StyledRadio
        {...rest}
        disabled = {disabled}
        size     = {size}
        checked  = {checked}
      />
      <RadioLabel size={size}>{label}</RadioLabel>
    </RadioGroup>
  );
};

标签: reactjstypescriptradio-buttonradioradio-group

解决方案


推荐阅读