首页 > 其他分享 >使用原生input实现单选按钮组

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

时间:2023-03-29 11:24:31浏览次数:44  
标签:box const 单选 item radio 按钮 input dirName

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;
}

效果:      

 

标签:box,const,单选,item,radio,按钮,input,dirName
From: https://www.cnblogs.com/zpy521hl/p/17268209.html

相关文章