如何使用 React Typescript 管理单选按钮状态?

How to manage radio button state with React Typescript?

我正在使用 React Typescript 实现一个简单的注册页面。 我正在尝试使用单选按钮设置性别,将其保存在状态中,并将其发送到服务器,但切换不起作用。 我该怎么办?

//RegisterPage.tsx
const [radioState, setradioState] = useState(null);
const [toggle, settoggle] = useState<boolean>(false);

const onRadioChange = (e: any) => {
    setradioState(e);
    console.log(radioState);
  };

const genderOps: ops[] = [
    { view: "man", value: "man" },
    { view: "woman", value: "woman" },
  ];
<div>
          {genderOps.map(({ title, gender }: any) => {
            return (
              <>
                <input
                  type="radio"
                  value={gender}
                  name={gender}
                  checked={gender === radioState}
                  onChange={(e) => onRadioChange(gender)}
                />
                {title}
              </>
            );
          })}
        </div>

您应该对代码做一些更改,这里是您应该做的:

import React, { EventHandler, useState } from "react";
import "./styles.css";

export default function App() {
  const [radioState, setradioState] = useState("");
  const [toggle, settoggle] = useState<boolean>(false);

  const onRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setradioState(e.currentTarget.value);
  };

  const genderOps = [
    { view: "man", value: "man" },
    { view: "woman", value: "woman" }
  ];
  return (
    <div className="App">
      <div>
        {genderOps.map(({ view: title, value: gender }: any) => {
          return (
            <>
              <input
                type="radio"
                value={gender}
                name={gender}
                checked={gender === radioState}
                onChange={(e) => onRadioChange(e)}
              />
              {title}
            </>
          );
        })}
      </div>{" "}
    </div>
  );
}