Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...