11

我正在使用react-hook-form存储表单数据,这些数据按照Codesandbox.io上的代码分为两页。我能够使用defaultValue={state.data.firstName}例如属性分配成功存储简单的文本输入(如名字、电子邮件等)......但我不知道如何使用 react 建议的模型将选中的项目存储在单选组中-钩形。我检查了他们的文档,不幸的是很少提及单选按钮组状态存储。这可以使用他们的 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);

在此先感谢您的帮助!

4

1 回答 1

8

我想你是这样的:

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

<input type="radio" defaultChecked={state.data.checked === 'xxx'} />
于 2020-01-10T12:27:23.693 回答