删除特定的数组元素,而不仅仅是最后一个 .pop - Redux-form

Remove specific array element, not just last one with .pop - Redux-form

https://codesandbox.io/s/qzm5q6xvx4

我已经创建了上面的codesandbox。我正在使用 redux-form ([https://redux-form.com]) that where you can add and remove fields to populate the form using .push and .pop 2.

使用 .pop 的问题它只删除最后一个数组元素,我希望每个 .push 创建的元素的选项都有自己的 "remove" 按钮,因此不仅仅是删除最后一个项目阵列。

我假设我需要分配 .pop 以某种方式查看匹配的反应 .map 元素?

const renderForm = ({ fields, label }) => (
  <div>
    <div
      variant="fab"
      color="primary"
      className="jr-fab-btn"
      aria-label="add"
      onClick={() => fields.push()}
    >
      ADD
    </div>
    <div
      variant="fab"
      color="primary"
      className="jr-fab-btn"
      aria-label="add"
      onClick={() => fields.pop()}
    >
      REMOVE
    </div>
    {fields.map((newIntel, index) => {
      console.log("newIntel", newIntel, index);
      return (
        <Field
          name={newIntel}
          key={index}
          label={label}
          placeholder={label}
          component={renderTextField}
          placeholder={label}
          label={label}
        />
      );
    })}
  </div>
);

欢迎提出任何想法。

如果您要查看作为 renderForm 道具的 fields,它包含一个方法 remove 来删除特定元素。只需将索引传递给它即可。 下面是您的组件的修改代码块。我已经做到了 class-component:

class renderForm extends React.Component {
 render(){
  let {fields, label} = this.props;
  const removeName = (index) => {
    fields = fields.remove(index);
  }
return(
  <div>
    <div
      variant="fab"
      color="primary"
      className="jr-fab-btn"
      aria-label="add"
      onClick={() => fields.push()}
    >
      ADD
</div>

    {fields.map((newIntel, index) => {
      console.log("newIntel", newIntel, index);
      return (
        <div>
          <Field
            name={newIntel}
            key={index}
            label={label}
            placeholder={label}
            component={renderTextField}
          />
          <p
            variant="fab"
            color="primary"
            style={{'cursor': 'pointer'}}
            className="jr-fab-btn"
            aria-label="add"
            onClick={() => removeName(index)}
          >
            REMOVE
      </p>
        </div>
      );
    })}
  </div>
 )
}}

希望您能轻松理解代码块。只需将上面的代码粘贴到您的 renderForm 组件的位置。它会像魔术一样工作。 :p