【问题标题】:How do I store the state of radio groups in React using react-hook-form如何使用 react-hook-form 在 React 中存储无线电组的状态
【发布时间】:2020-04-27 16:48:37
【问题描述】:

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

提前感谢您的帮助!

【问题讨论】:

  • 你的例子对我来说很好,单选按钮应该默认工作。
  • 请注意单选输入属性中没有defaultValue={state.data.RADIOBUTTONVALUE),这与firstName 和lastName 输入不同,它们有defaultValue={state.data.lastName}defaultValue={state.data.firstName}?这就是我所追求的......

标签: javascript reactjs react-hook-form


【解决方案1】:

我想你是这样的:

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

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

【讨论】:

猜你喜欢
  • 2021-10-21
  • 2022-12-21
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2021-04-16
  • 1970-01-01
相关资源
最近更新 更多