Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

reactjs - React collect child component data on some event from the parent component

In react best practice is Data flow from parent to child, event's will be passed from child to parent.

How to a  avoid anti pattern for this UI?

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):

  1. 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>
  1. 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What I usually do is to "lift the state up" to the parent. This means I would not break the natural React flow, that is passing props from the parent to the children. Following your example, I would put ALL the logic in the parent (submit function, form state, etc)

Const Parent = () => {
  const [formData, setFormData] = useState({})

  const onSubmitForm = () => {
      // send formData to somewhere
  }

  return (
      <ChildrenForm onChange={setFormData} formData={formData} />
      <button onSubmit={() => onSubmitForm()}>my button</button>
  )
}

Now I would use the onChange function inside the Children to update the formData everytime an input in the ChildrenForm changes. So all my state will be in the parent and I don't need to worry about having to pass everything up, from children to parent (antipattern as you mentioned)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...