我知道这是一个新手问题,但我陷入了困境,似乎找不到我要找的东西。
我有一个Typescript文件(.tsx)和四个答案选项。用户只能选择其中一个。然而,当用户点击多个单选按钮时,之前选择的按钮仍然保持选中状态。
我看到其他人使用以下方法:
<input type="radio"
value="option1"
checked={this.state.selectedOption === 'option1'}
onChange={this.handleOptionChange} />
对于某些人来说可能有效,但在我的 .tsx 文件中,我不能使用 this.state
。我找到的每个参考都是使用这种情况。
我尝试在我的 handleInputChange
函数中使用这个方法,但所有单选按钮都会被选中。
e.target.value === e.target.name ? setChecked(true) : setChecked(false)
下面是我拥有的代码,非常感谢您的任何建议。
// Quiz.tsx
import React, { useState } from "react"
interface Props {
questionnaire: any
}
const Quiz = (props: Props) => {
// setting checked state to false by default
const [checked, setChecked] = useState(false)
const handleInputChange = (e: any) => {
// if the current value equals the current input name, mark checked as true
// However this makes all radio buttons checked as true (all selected)
e.target.value === e.target.name ? setChecked(true) : setChecked(false)
}
{props.questionnaire.questions[currentQuestion].answers.map(
({ title, score }: any) => (
<>
<label>
<div>
<input
type="radio"
value={score}
name={score}
onChange={e => handleInputChange(e)}
checked={checked}
/>
{title}
</div>
</label>
</>
)
)}
}
any
是因为我不知道你的“问卷”类型,但你应该考虑添加正确的类型)。 - Taghi Khavari