我如何在React JS中使用选择选项来验证多个阵列控制器?

时间:2020-11-10 09:20:41

标签: reactjs react-hooks react-select react-hook-form

我正在使用React钩子表单进行简单的验证,但是我如何在errors.name之后取名字,因为我的名字太复杂了,无法更改该名字的后端原因

Here is an Code sandbox link of my example

任何人都可以帮助我。

这是我的代码:-

const App = () => {
const { control, handleSubmit, errors } = useForm();
const [target, setTarget] = useState([0]);
const addEmptyTargetFields = () => {
  setTarget((previousTarget: any) => [...previousTarget, target.length + 1]);
};

const removeTarget = (index: number) => {
  setTarget([...target.slice(0, index), ...target.slice(index + 1)]);
};

const onSubmit = () => {
  console.log("form submitted");
};

return (
  <form onSubmit={handleSubmit(onSubmit)}>
    <label>Ice Cream Preference</label>
    {target.map((e: any, i: number) => {
      return (
        <div key={i}>
          <Controller
            as={Select}
            control={control}
            name={`mediationRuleTargetList[${i}].networkId`}
            placeholder="Bidder"
            options={[
              { value: "chocolate", label: "Chocolate" },
              { value: "strawberry", label: "Strawberry" },
              { value: "vanilla", label: "Vanilla" }
            ]}
            rule={{ required: true }}
          />
          {errors.mediationRuleTargetList[${i}].networkId &&
            errors.mediationRuleTargetList[${i}].networkId ===
              "required" && <span>Bidders is required</span>}
          <Controller
            as={Select}
            control={control}
            name={`mediationRuleTargetList[${i}].ecpmLookBackPeriod`}
            placeholder="eCPM look back period"
            options={[
              { value: "chocolate", label: "Chocolate" },
              { value: "strawberry", label: "Strawberry" },
              { value: "vanilla", label: "Vanilla" }
            ]}
            rule={{ required: true }}
          />
          {errors.mediationRuleTargetList[${i}].ecpmLookBackPeriod &&
            errors.mediationRuleTargetList[${i}].ecpmLookBackPeriod.type ===
              "required" && <span>Bidders is required</span>}
          {i > 0 && <button onClick={() => removeTarget(i)} />}
        </div>
      );
    })}
    <button onClick={() => addEmptyTargetFields()}>Add More</button>
    <input type="submit" />
  </form>
 );
};

0 个答案:

没有答案