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

148
Views
¿Puede un componente funcional React (moderno) exponer un método con estado externamente?

¿Puede mi componente funcional React exponer externamente un método con acceso al estado interno?

 interface Inner { foo: string } function Inner(props: Inner) { const [foo, setFoo] = useState<string>(props.foo + "baz") function doTheThing() { console.log(`doin' that ${foo} thing`) } return <div>{props.foo}</div> } function Outer() { const inner = <Inner foo="bar" /> return ( <> <button onClick={() => inner.doTheThing()}> Do That Thing </button> {inner} </> ) }

Por supuesto, esto me da un error: TypeError: inner.doTheThing is not a function .

Puedo usar un componente de clase para exponer un método como este. Pero, ¿hay alguna forma (¿con ganchos? ¿con referencias?) de hacer que esto funcione con un componente funcional?

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

0

Puede pasar una referencia y luego almacenar la referencia de doTheThing allí.

 import { MutableRefObject, useRef, useState } from "react"; interface Inner { foo: string; dRef: MutableRefObject<{ doTheThing: () => void } | undefined>; } function Inner(props: Inner) { const [foo, setFoo] = useState<string>(props.foo + "baz"); function doTheThing() { console.log(`doin' that ${foo} thing`); } props.dRef.current = { doTheThing }; return <div>{props.foo}</div>; } export function Outer() { const dRef = useRef<{ doTheThing: () => void }>(); const inner = <Inner foo="bar" dRef={dRef} />; return ( <> <button onClick={() => dRef.current?.doTheThing()}>Do That Thing</button> {inner} </> ); }
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!