The difference between a function component and a class component to trigger children form changes in Ant design
Sometimes we need to trigger the changes in a children form, then the parent component can do something in consistent. For example, put a form in a drawer to CRUD some information. Also, you want to monitor the items validation out of the form.
To transfer the state, we need to use ref to monitor the changes. However, the way of using ref is different for a class component from a function component when using hook. Here we will discuss the both way in React / Antd.
The example we used here is to monitor the items' validation status for two children forms. the whole structure is looks like this:
There parent component is a card, and there're two forms inside, left referee details and right questions. When we submit the page, we hope to get the status of the both children forms.
Example codes for children parts
In this case we use class component for the left side, and use function component for the right one.
It could be seen, for the class children component, we don't need to do anything in it to get the status, all the efforts are outside it. In term of the function one, we need to use useImperativeHandle and forwardRef.
useImperativeHandle` customizes the instance value that is exposed to parent components when using `ref
Example codes for the parent part
For the parent component, we need to generate the both ref and use them, the codes are looks like this:
To ref the form, we use wrappedComponentRef to get the instance.
Then it is easy to get the validation status for both forms through the ref instances. The codes are:
const validateLeft=()=>{
const {form} =formRef.props
let result = true
form.validateFields((errors, values) => {
if (errors) {
result=false;
}
});
return result
}
const validateRight=()=>{
let result = true
questionFormRef.validateFields((errors, values) => {
if (errors) {
result=false;
}
});
return result
}
You might notice, for the class component, we get the form instance by using const {form} =formRef.props . In terms of the hook one, because we send back the "form" in the props, we can use questionFormRef instance directly.
Source
https://3x.ant.design/components/form/
https://reactjs.org/docs/hooks-reference.html