在父组件中访问 form(react-final-form) 状态

Access form(react-final-form) state in the parent component

如何访问父组件中的表单状态

这就是我正在做的(只是一个简短的代码,请忽略语法)

class Parent {
   <listComponent
     onSelect: handler
   >
  handler() {
    // Do this only if the already opened ChildComp in not dirty
     <ChildComp>
  }
}
// Uses react-final-form
class ChildComp {
   <form
      onSubmit: handleSubmit
      render: renderForm
    >
     renderForm ({dirty}){
      // Assigning to a class variable and prompting for unsaved changes which I am able to do
       this.isFormDirty = dirty
      return(
         <InputField>
     );
   }
   </form>
}

现在的问题是,如果在 onSelect handler() 中子项脏了,我无法通知父项不要渲染子项。 我不能在 render 方法中执行 setState,至少我可以使用 componentDidUpdate 通知 提前致谢

复制自Issue #551


另一种可能性是最近 API 将 lets you provide your own form instance 更改为 <Form>,因此这样的事情可能有效:

import { createForm } from 'final-form'

function TestForm() {
  const formRef = React.useRef(createForm({
    onSubmit: myOnSubmit
  })
  return (
    <div>
      <Form form={formRef.current}>
        {({ handleSubmit, form }) => (
          <form onSubmit={handleSubmit}> ... fields ... </form>
        )}
      </Form>
      <button onClick={() => formRef.current.reset()}>Reset</button>
    </div>
  )
}