首页 > 解决方案 > 如何使用带有文件类型输入的 Redux-Form 字段数组

问题描述

在 redux-form 中,当创建 的输入字段数组时type="file"Fields.remove(index)会弹出而不是删除。

我认为这可能与github 上 #2666key={index}中讨论的使用有关,但使用唯一生成的密钥并不能修复此错误。

如何Fields.remove(index)使用数组正常工作input type="file"

import React from "react";
import { reduxForm, Field, FieldArray } from "redux-form";

const Guid = () => {
  const s4 = () =>
    Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  return `${s4()}`;
};

const renderField = ({ fields, input, handleDelete, index, label }) => (
  <div>
    <input type="file" {...input} />
    <label>
      {" "}
      - id: {label}, index = {index}
    </label>
  </div>
);

const renderFieldList = ({ fields }) => (
  <div>
    {fields.map((field, index) => {
      const { id } = fields.get(index);
      return (
        <div key={index}>
          <Field
            name={field}
            component={renderField}
            index={index}
            label={id}
          />
          <button type="button" onClick={() => fields.remove(index)}>
            Delete
          </button>
        </div>
      );
    })}

    <button type="button" onClick={() => fields.push({ id: Guid() })}>
      Add
    </button>
  </div>
);

const MyForm = ({ handleSubmit }) => (
  <form onSubmit={handleSubmit}>
    <FieldArray name="foo" component={renderFieldList} />
  </form>
);

export default reduxForm({
  form: "form",

  onSubmit: values => {
    window.alert(JSON.stringify(values, null, 2));
  }
})(MyForm);

例子

标签: javascriptreactjsindexingredux-form

解决方案


推荐阅读