问题描述
嘿,我想为数组中的每个项目创建一个单选按钮列表。目前我的项目工作正常,但不是单选按钮,因为它们都是可选的。
解决方法
你必须设置 name 属性才能只选择一个
这是小提琴:https://codesandbox.io/s/mystifying-brown-m7f4k
<label>
{answer.text}
{question.single ? (
<input
type="radio"
onChange={onChange(question.id,answer.id)}
/>
) : (
<input
type="checkbox"
name={`radio_${question.id}`}
onChange={onClick(question.id,answer.id)}
/>
)}
</label>
,
你标记了 material-ui 但沙箱似乎没有使用 material-ui。
无论如何,在 material-ui 中,您可以使用 RadioGroup 使其中一个单选按钮可选。
就像material-ui文档中的这个例子:
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup aria-label="gender" name="gender1" value={value} onChange={handleChange}>
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
</RadioGroup>
</FormControl>
他们还有另一种使用独立单选按钮的方法
检查:https://material-ui.com/components/radio-buttons/#standalone-radio-buttons
如果您使用的是 HTML Radio Buttons 而不是 material-ui
然后在输入中使用 name 属性
就像这样:
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
,
您必须添加具有相同值的 name 属性。
例如:
<form action="/action_page.php">
<p>Please select your gender: <b>(With same name)</b></p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<br>
<p>Please select your gender:<b>(With diferent name)</b> </p>
<input type="radio" id="male" name="gender1" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender2" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender3" value="other">
<label for="other">Other</label>
</form>