如何在父组件中访问表单状态
这就是我正在做的(只是简短的代码,请忽略语法)
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进行通知 预先感谢
答案 0 :(得分:0)
从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>
)
}