Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

341
Views
Llamar a la función del componente secundario desde el componente principal da error: no se pueden leer las propiedades de undefined

Tengo un componente secundario como este.

Padre => Subpadre => Hijo

Tengo una función en Child Component y necesito llamar a esta función en Parent. Para hacer esto, uso React Hooks. (Me refiero a este artículo para hacer esto. Porque soy un estudiante nuevo para reatjs).

Este es mi código.

 import React, {forwardRef, useRef, useImperativeHandle} from 'react'; import {Button} from '@material-ui/core'; function Parent(props) { const childRef = useRef(); const addDate = () =>{ childRef && childRef.current.submitHandler(); }; return ( <div> {/* eslint-disable-next-line react/jsx-no-undef */} <Button onClick={addDate}> SAVE </Button> <SubParent ref={childRef}/> </div> ); } function SubParent(props) { return ( <div> <Child ref={props.ref}/> </div> ); } const Child = forwardRef((props, ref) => { const submitHandler = () => {}; useImperativeHandle( ref, () => ({ submitHandler, }), ); return ( <div>Child Component</div> ); });

Pero cuando presiono el botón en el componente principal, tengo este error.

Enlace de imagen de error

TypeError: no se pueden leer las propiedades de undefined (leyendo 'submitHandler')

No puedo encontrar mi error. Si alguien me puede ayudar con esto, realmente lo aprecio. Muchas gracias.❤️

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Creo que estás en el camino correcto. Sin embargo, solo necesita reenviar la referencia del componente SubParent , de lo contrario, se adjuntará al componente SubParent en lugar del componente Child .

Aquí está la caja de códigos: https://codesandbox.io/s/vigorous-hooks-o5n5s?file=/src/App.js:215-780

 function Parent(props) { const childRef = useRef(); const addDate = () => { childRef && childRef.current.submitHandler(); }; return ( <div> <Button onClick={addDate}>SAVE</Button> <SubParent ref={childRef} /> </div> ); } const SubParent = React.forwardRef((props, ref) => ( // check this implementation <div> <Child ref={ref} /> </div> )); const Child = forwardRef((props, ref) => { const submitHandler = () => { console.log("Called"); }; useImperativeHandle(ref, () => ({ submitHandler })); return <div>Child Component</div>; });
about 4 years ago · Juan Pablo Isaza Report

0

No puede reenviar la referencia desde el objeto de accesorios predeterminado en el componente SubParent intermedio ya que la referencia no se pasa de esta manera.

de referencias de reenvío a componentes DOM

Los componentes de función o clase regulares no reciben el argumento ref, y ref tampoco está disponible en props.

Deberá aplicar un forwardRef() a cada componente entre el padre y el hijo final.

 const { forwardRef, useRef, useImperativeHandle } = React; function Parent(props) { const childRef = useRef(); const addDate = () => { childRef && childRef.current.submitHandler(); }; return ( <div> <button onClick={addDate}>SAVE</button> <SubParent ref={childRef} /> </div> ); } const SubParent = forwardRef((props, ref) => { return ( <div> <Child ref={ref} /> </div> ); }); const Child = forwardRef((props, ref) => { const submitHandler = () => { console.log('In submit handler'); }; useImperativeHandle(ref, () => ({ submitHandler })); return <div>Child Component</div>; }); ReactDOM.render(<Parent />, document.getElementById('root'));
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Casi hiciste todo, pero solo un punto, necesitas pasar forwardRef en lugar de ref al SubParent :

 import React, { forwardRef, useRef, useImperativeHandle } from "react"; import { Button } from "@material-ui/core"; function Parent(props) { const childRef = useRef(); const addDate = () => { console.log("from parent component"); childRef?.current?.submitHandler(); }; return ( <div> <Button onClick={addDate}>SAVE</Button> <SubParent forwardRef={childRef} /> </div> ); } function SubParent(props) { return ( <div> <Child ref={props.forwardRef} /> </div> ); } const Child = forwardRef((props, ref) => { const submitHandler = () => { console.log("from child component"); }; useImperativeHandle(ref, () => ({ submitHandler: submitHandler })); return <div>Child Component</div>; }); export default Parent;

Pruébate los códigos y la caja

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!