如何在TypeScript React中切换单选按钮?

3

我知道这是一个新手问题,但我陷入了困境,似乎找不到我要找的东西。

我有一个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>
      </>
    )
  )}
}


1个回答

0
你的代码应该像这样: (我只使用any,因为我不知道你的questionnaire类型,但你应该考虑添加正确的类型)
import React, { useState } from "react";

interface Props {
  questionnaire: any;
}

const Quiz = (props: Props) => {
  const [checkBox, setCheckBox] = useState();

  const handleInputChange = (score: any) => {
    setCheckBox(score);
  };

  return (
    // <-- Here you need to return something from component
    <>
     {
       props.questionnaire.questions[currentQuestion].answers.map((
      {title, score}: any) => (
        <label>
          <div>
            <input
              type="radio"
              value={score}
              name={score}
              onChange={e => handleInputChange(score)}
              checked={score === checkBox}
            />
            {title}
          </div>
        </label>
      )
    }
    </>
  );
};



1
完美运行!感谢您帮我解决了这个问题! - Kayla
1
为什么使用任意类型? - DoubleM
@DoubleM,我在我的答案中已经解释了原因(我仅使用any是因为我不知道你的“问卷”类型,但你应该考虑添加正确的类型)。 - Taghi Khavari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接