【问题标题】:Specify initial value for radio button指定单选按钮的初始值
【发布时间】:2020-08-18 15:41:27
【问题描述】:

我想在打开表单时选中“精确”单选按钮:

<Form
      onSubmit={onSubmit}
      initialValues={{ match_type: "exact" }}
      render={({ handleSubmit, form, reset, submitting, pristine, values }) => (
        <form
          onSubmit={() => {
            handleSubmit();
          }}
        >
          <fieldset>
            <legend>Match type</legend>
            <Field name="match_type">
              {({ input }) => (
                <label>
                  <input {...input} type="radio" value="fuzzy" /> Fuzzy
                </label>
              )}
            </Field>
            <Field name="match_type">
              {({ input }) => (
                <label>
                  <input {...input} type="radio" value="exact" /> Exact
                </label>
              )}
            </Field>
          </fieldset>
          <button type="submit">Save match</button>
        </form>
      )}
    />

单选按钮保持未选中状态。知道我应该如何让它工作吗?注意使用&lt;Field component="input" type="radio" .../&gt; 对我来说不是一个选项。

代码沙盒:https://codesandbox.io/s/react-final-form-reset-after-submit-forked-q6jyv?file=/index.js:359-1235

【问题讨论】:

  • 尝试对指定输入使用 defaultChecked={true}
  • 或者checked属性怎么样
  • 这两种方法都不会为最终表单的状态提供值。

标签: reactjs react-final-form final-form


【解决方案1】:

你可以在标签中设置默认勾选。

<input {...input} type="radio" value="exact" checked />

【讨论】:

  • 请注意,如果我这样做,输入将不会将其值提供给 React Final Form。
  • 删除输入的 HTML 标记并将所有内容添加到 &lt;Field&gt; 组件。 &lt;Field name="match_type" component="input" type="radio" value="exact" /&gt;{' '}Exact
【解决方案2】:

我只需要正确使用Field 组件:

<Field name="match_type" type="radio" value="fuzzy">
  {({ input }) => (
    <label>
      <input {...input} /> Fuzzy
    </label>
  )}
</Field>

这样&lt;input 将得到它需要的从参数传播到渲染道具。

【讨论】:

    【解决方案3】:

    如果您在提供的代码框中检查您的组件,您会发现 Field 组件没有 value 属性。我在这里附上截图

    您有几个选项可以解决这个问题。主要思想是了解您在说 {...input} 时传递的内容

    input={{ name: 'match_type', value: 'exact', onChange: (e) => (whatever you need on change) }}
    

    RFF 仅设置这样的值可能会很棘手,因为事实来源存在于表单中。因此,您还可以使用表单的 mutator 功能。 This is很好地描述了如何做到这一点

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 2012-03-23
      • 2015-09-04
      • 2011-06-10
      • 2016-10-02
      • 2020-11-05
      • 2011-06-10
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多