使用原生input实现单选按钮组

复制代码
type RadioType = {
  bottomHeight?: number;
  name: string;
  label: string;
  dirNameList: string[];
  required?: boolean;
  onChange?: (value: string) => void
};

export const Radio: FC<RadioType> = ({
  bottomHeight = 10,
  name = '',
  label = '',
  required = true,
  dirNameList = ['None', 'Yes'],
  onChange = () => { }
}) => {
  const [radioCheckedList, setRadioCheckedList] = useState((dirNameList || []).map(item => ({ name: name, dirName: item, checked: false })));

  const handleRadioChange = (e: any) => {
    onChange(e.target.dirName)
    const newRadioCheckedList = radioCheckedList.map(item => {
      if (item.dirName === e.target.dirName) {
        return ({
          ...item,
          checked: true
        })
      } else {
        return ({
          ...item,
          checked: false
        })
      }
    })
    setRadioCheckedList(newRadioCheckedList)

  }
  return (
    <div className={style['lvc-en-input']}>
      <label className={required ? style['label-required'] : ''}>{label}</label>
      {(radioCheckedList || []).map(item => {
        const other = {
          dirName: item.dirName,
        }
        return (
          <>
            <label className={style['radio-box']} htmlFor="no">
              <input
                className="lvc-en-input"
                type="radio"
                name={item.name}
                required={required}
                onChange={handleRadioChange}
                checked={item.checked}
                {...other}
              />
              {item.dirName}
            </label>
            <div style={{ height: `${bottomHeight}px` }}></div>
          </>
        )
      })}
    </div>
  );
}
复制代码

使用:

<Radio name={'isDietaryRestriction'} label={"Any Dietary Restrictions"} required onChange={handleRadioChange} dirNameList={['None', 'Yes']} />

CSS:

复制代码
label.radio-box {
  padding-left: 30px;
  font-weight: normal;
  position: relative;
  display: inline-block;
}

.radio-box input[type="radio"]::before {
  content: '';
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #ddd;
  position: absolute;
  top: 4px;
  left: 0;
}

.radio-box input[type="radio"]:checked::before {
  background-clip: content-box;
  background-color: #ccac77;
  width: 10px;
  height: 10px;
  padding: 5px;
}

.radio-box input[type="radio"] {
  width: 0;
  height: 0;
  // ios手机上会有一个小黑点,用颜色试试去掉黑点
  color: #fff;
  border-color: #fff;
}
复制代码

效果:      

 

posted @   飞奔的程序员  阅读(310)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示