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

How to toggle a radio button in Typescript React?

我知道这是一个菜鸟问题,但我卡住了,似乎找不到我要找的东西。

我有一个 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 只是因为我不知道你的 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>
      )
    }
    </>
  );
};