如何处理以文本字段为标签的单选按钮的输入



我很难获得以文本字段为标签的单选按钮的输入。

当旁边的文本字段接收用户输入时,我也很难动态地"检查"单选按钮。

它的最终目标是让它像谷歌表单一样工作,用户在做一个MCQ问题,他/她选择"其他"选项,然后在文本字段中写一些文本。我希望能够在一个名为selectedRadioButton的对象中捕获输入文本,然后将selectedRadio巴顿附加到一个存储所有响应的数组中

我遇到的另一个问题是,我似乎无法捕获整个输入字符串,因为当我将输入的最后一个字符添加到对象状态时,它被切掉了。我的最后一个问题是,如何确保在不截断任何内容的情况下捕获整个输入字符串?

这就是我的UI的样子,你可以看到"所有响应"数组中的规范值并没有显示整个文本输入。我的代码

我用于处理标签中有文本字段的单选按钮输入的代码(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>
)
);

以下是如何在<FormControlLabel />:中从<Input />收集文本的工作示例


import React, { useState } from "react";
import { FormControlLabel, Radio, TextField } from '@material-ui/core';
export default function OtherInput() {
const [ checked, setChecked ] = useState(false);
const [ otherInfo, setOtherInfo ] = useState('');
return (
<div>
<h1>"Other" Radio Input with Hook:</h1>
<h2>Checked: {checked.toString()} </h2>
<h2>Input result: {otherInfo} </h2>
<FormControlLabel
control={
<Radio
checked={checked}
onClick={() => setChecked(!checked)}
value="other"
color='primary'
label='other'/>
}
label={
checked ?
<TextField
disabled={!checked}
label="Please Specify"
onKeyDown={(e) => setOtherInfo(e.target.value)}/>
: 'Other'
}/>
</div>
);
}

示例代码沙盒:https://codesandbox.io/s/stack-65535893-otherinput-4hpm7?file=/src/OtherInput.js