繁体   English   中英

如何使用 react-hook-form 在 React 中存储无线电组的状态

[英]How do I store the state of radio groups in React using react-hook-form

我正在使用react-hook-form来存储表单数据,这些数据根据Codesandbox.io 上看到的代码分成两页。 例如,我能够使用defaultValue={state.data.firstName}等属性分配成功存储简单的文本输入(如名字、电子邮件等)……但我不知道如何将选中的项目存储在无线电组使用 react-hook-form 建议的模型。 我检查了他们的文档,遗憾的是很少提到单选按钮组状态存储。 这可以使用他们的 API 吗?

import React from "react";
import { useForm } from "react-hook-form";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";

const Step1 = props => {
  const { register, handleSubmit, errors } = useForm();
  const { action, state } = useStateMachine(updateAction);
  const onSubit = data => {
    action(data);
    props.history.push("./step2");
  };

  return (
    <form onSubmit={handleSubmit(onSubit)}>
      <h2>Step 1</h2>
      <label>
        First Name:
        <input
          name="firstName"
          ref={register}
          defaultValue={state.data.firstName}
        />
      </label>
      <label>
        Last Name:
        <input
          name="lastName"
          ref={register}
          defaultValue={state.data.lastName}
        />
      </label>

      <label className="control-label" htmlFor="vehicles">How many vehicles do you own?<br />
        <input type="radio" name="vehicles" id="vehicles-1" value="1"
          ref={register({ required: true })} className="radio" />
        <label class="radio">1</label>

        <input type="radio" name="vehicles" id="vehicles-2" value="2"
          ref={register({ required: true })} className="radio" />
        <label class="radio">2</label>
        {errors.vehicles && <div className="form_error">Number of Vehicles is required</div>}
      </label>

      <input type="submit" />
    </form>
  );
};

export default withRouter(Step1);

在此先感谢您的帮助!

我认为你在追求这个:

https://reactjs.org/docs/uncontrolled-components.html

<input type="radio" defaultChecked={state.data.checked === 'xxx'} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM