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
245 views
in Technique[技术] by (71.8m points)

javascript - How to trigger child component function

I am trying to reducing my code complexity to express by defining just skeleton code bellow. have to trigger the toggleModel of the child component

import React, { useState } from "react";
import "./styles.css";

const ChildComponent = (props) => {
  // .... some useStates 
  const toggleModel = () => {
    // have to trigger this methoud once user clicks on button
    // have to change some states here 
  };
  return (
     <div>
       {props.children}
        ...... other things .......
     </div>
  );
};

export default function ParentComponet() {
  return (
    <div className="App">
      Hello
      <ChildComponent>
        <button
          type="button"
          onClick={() => {
            // here i have to trigger the toggleModel function of ChildComponent
          }}
        >
          Toggle Model
        </button>
      </ChildComponent>
    </div>
  );
}

i am rendering child component by sending children elements, have to trigger the toggleModel of the child component it will reduce my 70 % redundant code at our application. is there any way to achieve the same codesandbox. Thank you in advance


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

1 Answer

0 votes
by (71.8m points)

You can take a look at this question here, it can help you.

But I would say it's not a good practice to call a child function from the parent. Usually what I would do is to "lift up" the method to the parent, and pass down to the child if possible.


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

...