如何解决如何使用文本字段作为标签处理 Radiobutton 的输入
当旁边的文本字段接收用户输入时,我也很难动态“检查”单选按钮。
它的最终目标是使其功能类似于 Google 表单,用户在其中执行 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 />
中的 <FormControlLabel />
收集文本的工作示例:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。