Soy nuevo en reaccionar. Básicamente, quiero que cuando haga clic en el botón del componente secundario, se llame a la función myFunction desde el componente principal. ¿Cómo puedo hacerlo?
import "./styles.css"; export const Parent = ({ children }) => { //I need excecute myFunction when user click return ( <div> I am parent <br /> <br /> {children} </div> ); }; export const Child = () => { const myFunction = () => { console.log("say hello from parent"); }; return ( <div> I am children <br /> <button>Send function to execute in the parent</button> </div> ); }; export default function App() { return ( <Parent> <Child /> </Parent> ); }Intente llamar al niño dentro de la función principal como se muestra a continuación:
import "./styles.css"; export const Child = (props) => { const myFunction = () => { console.log("say hello from parent"); }; return ( <div> I am children <br /> <button onClick={props.randomFun} >Send function to execute in the parent</button> </div> ); }; export const Parent = () => { //I need excecute myFunction when user click const handleChild=()=>{console.log("You clicked on child button")} return ( <div> I am parent <br /> <br /> <child randomFun = {handleChild} /> </div> ); }; export default function App() { return ( <Parent /> ); }Podemos usar useRef ,
Aquí tenemos un componente principal con un botón y un componente secundario con una función para mostrar una alerta. Si desea llamar a la función showAlert cuando se hace clic en el botón, no hay una forma directa de acceder a ella.
import { forwardRef, useRef, useImperativeHandle } from "react" const ChildComp = forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ showAlert() { alert("Hello from Child Component") }, })) return <div></div> }) function App() { const childCompRef = useRef() return ( <div> <button onClick={() => childCompRef.current.showAlert()}>Click Me</button> <ChildComp ref={childCompRef} /> </div> ) } export default App¿Tu quieres esto?
export const Child = () => { const myFunction = () => { console.log("say hello from parent"); }; return ( <div> I am children <br /> <button onClick={()=>myFunction()}>Send function to execute in the parent</button> </div> ); };