简体   繁体   English

如何防止 react-final-form 呈现特定输入

[英]How to prevent react-final-form from rendering an specific input

I have a react-final-form form, which has 2 inputs.我有一个react-final-form表单,它有 2 个输入。 Let's call them from and to .让我们调用它们fromto

What I want to do is that whenever input from changes, I set a value for input to based on input from 's value.我想要做的是,每当输入更改时,我都会根据输入值设置输入值。

I do that in validate function because i don't know where else i can do that.我这样做是为了validate function 因为我不知道我还能在哪里做到这一点。 And it causes re-rendering the component in a loop.它会导致在循环中重新渲染组件。

Since I change the value of to in validate, it causes validate function to run again and again and again.由于我在验证中将值更改,它会导致验证function 一次又一次地运行。 How can I avoid that?我怎样才能避免这种情况?

The actual code is much more complex than this but this is where i run into problems.实际代码比这复杂得多,但这是我遇到问题的地方。

Thanks谢谢

const validate = (v) => {
  const calculateFrom = calculate(v.from);

  window.setTo(calculateFrom);
};
<Form
  onSubmit={onSubmit}
  validate={validate}
  mutators={{
    setTo: (a, s, u) => {
      u.changeValue(s, 'to', () => a[0]);
    },
    setMax: (a, s, u) => {
      u.changeValue(s, 'from', () => getMaxBalance(selectedAsset1));
    },
  }}
  subscription={{ submitting: true, pristine: true }}
  render={({
    form,
    pristine,
    invalid,
    handleSubmit,
  }) => {
    if (!window.setTo) {
      window.setTo = form.mutators.setTo;
    }

    return (
      <form onSubmit={handleSubmit}>
<Field name="from">
  {({ input, meta }) => (
    <Input
      type="number"
      placeholder="123"
      size="input-medium"
      input={input}
      meta={meta}
    />
  )}
</Field>

<Field name="to">
  {({ input, meta }) => (
    <Input
      type="number"
      placeholder="123"
      size="input-medium"
      input={input}
      meta={meta}
    />
  )}
</Field>
/>

First of all you could use an existing decorator https://codesandbox.io/s/oq52p6v96y首先,您可以使用现有的装饰器https://codesandbox.io/s/oq52p6v96y

I'm not really sure why it is re-rendering infinitely.我不太确定为什么它会无限地重新渲染。 Might have something to do with reusing the function setTo that you put on the window.可能与重用 window 上的 function setTo 有关。

If you don't want to add that mutator library I'd try the following solutions.如果您不想添加该 mutator 库,我会尝试以下解决方案。 use parse prop on the the Field where you can get the value and compare it with the other value that you need and return exactly what is should be check attached example parse prop字段上使用解析道具,您可以在其中获取值并将其与您需要的其他值进行比较,并准确返回应该检查附加的示例解析道具

Final form allows to nest Fields inside custom components so you could just handle everything there by using useForm hook最终表单允许将字段嵌套在自定义组件中,因此您可以使用useForm钩子处理那里的所有内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM