使用原生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; }
效果:
分类:
js相关
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!