首页 > 解决方案 > 如何根据另一个数字输入中的数字动态创建多个字段?

问题描述

我想要这种行为,下面是代码片段:

当字段 X 更改其数字(整数)值时(通过用户交互):

  1. 如果现在 X 的值更大,则将新字段添加到字段数组(称为 A)直到有 X 个字段(数组中的字段应该是number-typed 或<select>s)

  2. 否则,如果现在 X 的值较低,则删除字段数组 A 中的最后一个字段,直到只有 X 个字段

这是我的出发点:

const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
  {
    control,
    name: "A",
  }
);

watch((data, options) => {
  // console.log('d, o', data, options);

  if (options.name === 'X') {
    let z = data.X;
    while (z) {
      // remove?
      --z;
    }
  }
});

在文档中,据说不会在单个渲染中放置多个删除调用,如果输入不会以会影响现有值的方式更改其值(因此应保留 A 中的值),我还希望保留现有值.

我也使用它,但它是组件的另一部分应该没问题:

{X > 0 && (
    <div>
        {fields.map((field, index) => {
...

我可以在纯 React 中做到这一点,但我正在使用 react-hook-form 模块,我正在徘徊如何在不放弃 react-hook-form 依赖的情况下实现这种想要的行为。

请帮我!谢谢!

标签: reactjstypescriptreact-hook-form

解决方案


我在同一个包 react-hook-form 中使用了 Controller 组件。

if (f.type === "multiple") {
  return (
    f.condition() && (
      <Controller
        control={control}
        name={f.name}
        defaultValue={[]}
        render={({
          field: { onChange, onBlur, value, name, ref },
          fieldState: { invalid, isTouched, isDirty, error },
          formState,
        }) => {
          let seq = [];
          const x = f.count();
          for (let i = 0; i < x; i++) {
            seq.push(i);
          }

          return (
            <div tabIndex={0} onBlur={onBlur} ref={ref}>
              {seq.map((field, index) => {
                return (
                  <React.Fragment key={index}>
                    {f.renderChild({ index, onChange })}
                  </React.Fragment>
                );
              })}
            </div>
          );
        }}
      />
    )
  );
}

推荐阅读