【发布时间】:2023-03-23 03:20:01
【问题描述】:
我正在努力获取以文本字段作为标签的单选按钮的输入。
当旁边的文本字段接收用户输入时,我也很难动态地“检查”单选按钮。
它的最终目标是让它像谷歌表单一样运行,用户正在做一个 MCQ 问题,他/她选择“其他”选项,然后在文本字段中写一些文本。我希望能够在名为 selectedRadioButton 的对象中捕获输入文本,然后将 selectedRadioButton 附加到存储所有响应的数组中。
我遇到的另一个问题是我似乎无法捕获整个输入字符串,因为当我将输入的最后一个字符添加到对象状态时,它被切掉了。我的最后一个问题是,如何确保捕获整个输入字符串而不切掉任何内容?
这是我的 UI 的样子,您可以看到“所有响应”数组中的规范值没有显示整个文本输入。 my code
我用于处理标签中包含文本字段的单选按钮输入的代码 (className="customOption"):
// singleSelectQuestions is contains a function that returns jsx, which displays the suitable components based on the question attributes.
// In this case, all questions should be wrapped around by radio button components because they're all single select
const singleSelectQuestions = currQuestion.answerOptions.map(
({ answerText, price }) =>
answerText !== "Custom" ? (
<FormControlLabel
value={answerText}
control={<Radio />} // normal radio button
label={answerText}
price={price}
// We need to capture the selected answer option and the price into a state for each option
// The we will pass this state (object) into the hook that handles updating the entire response object
onClick={() =>
updateSelectedRadioButton({
selectedAnswer: answerText,
price: price,
})
}
/>
) : (
<div className="customOption">
<FormControlLabel
control={<Radio />}
value={answerText}
price={price}
floatingLabelFixed={true}
label={
<TextField
required
label="Please Specify"
onKeyDown={(e) => updateSpecifications(e.target.value)}
/>
}
onClick={() =>
updateSelectedRadioButton({
selectedAnswer: answerText,
specifications: specifications,
price: 0,
})
}
/>
</div>
)
);
【问题讨论】:
-
看起来很有趣的功能!我在下面发布了回复,以回答您有关从
<Input />收集文本的问题,如果这有帮助,请告诉我。对于您的其他问题,也许为每个剩余的问题打开一个新问题。
标签: reactjs react-hooks material-ui qradiobutton