In react best practice is Data flow from parent to child, event's will be passed from child to parent.
In this UI we have a parent component which contains 2 child components with forms. We now have to gather data from child components when the user clicks on the submit button in the parent.
Possible solutions (Bad solutions | anti pattern):
- Pass ref from child and trigger child method from parent to collect data (Accessing child method from parent not a good idea)
<Parent>
onFormData(data) {
//here collect data from child
}
onSubmit() {
//Trigger a method onData in child
aRef.collectData()
}
<child-A ref={aRef} onData={onFormData}></Child-A>
<Child-B ref={bRef} onData={onFormData}></Child-B>
<button onClick={onSubmit}>Submit</Submit>
</Parent>
- Bind a props to child, on submit click change value of prop with dummy value. Observe same prop in useEffect hook ( Really bad solution)
<Parent>
onFormData(data) {
//here collect data from child
}
onSubmit() {
//update randomValue, which will be observed in useEffect that calls onData method from child
randomValue = Math.random();
}
<child-A triggerSubmit={randomValue} onData={onFormData}></Child-A>
<Child-B triggerSubmit={randomValue} onData={onFormData}></Child-B>
<button onClick={onSubmit}>Submit</Submit>
</Parent>
Is there any other best approach for handling these scenario? How to a avoid anti pattern for this UI?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…