简体   繁体   中英

How to call parent component method from component/reactnode passed as props in React

I am passing Button component as props of Toast component, so my custom button will be displayed inside toast component. If I click on button I need to call a method inside Toast component.

Toast usage:

const customActionButtonTemplate = ( 
<Mybutton label="Hide" onClick={// Here I wan t to call Toast components hideToast method//} />);

<Toast (...args)
customActionButtonTemplate = {customActionButtonTemplate()} />

Toast component:

export const Toast.FC<ToastInuts> = (props: ToastInputs ) => {
const hideToast(): void => {
   //toast clicked
}

return (
<div>
  <div>
    //contents
  </div>
  <div>
   {props.customActionButtonTemplate}
  </div>
</div>
)

};
const [hidden, setHidden] = useState(false);

const customActionButtonTemplate = ( 
<Mybutton label="Hide" onClick={()=>hideToast(!hidden)} />);

<Toast (...args, hidden)
customActionButtonTemplate = {customActionButtonTemplate()} />

You extract state, setHidden function will be passed to button that you want, and you will just pass value of hidden to Toast, based on which you will hide or not hide the Toast

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM