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

219
Views
usar ref.current como contenedor en el portal de reacción lanza el contenedor de destino no es un elemento DOM

Estoy usando el portal de reacción para representar dentro del elemento dom representado por el elemento principal

 import { useRef, useState } from "react"; import { createPortal } from "react-dom"; export default function App() { const pageTitleRef = useRef(null); const [page, setPage] = useState(true); return ( <div className="App"> <header> <h1> App-<span id="page-title" ref={pageTitleRef}></span> </h1> <button onClick={(e) => { setPage((p) => !p); }} > toggle page </button> </header> {page ? ( <Page1 key="page1" pageTitleRef={pageTitleRef} /> ) : ( <Page2 key="page2" pageTitleRef={pageTitleRef} /> )} </div> ); } function Page1({ pageTitleRef }) { return ( <div className="Page1"> {createPortal("Page2 title", pageTitleRef.current)} <h2>Page 1 content!</h2> </div> ); } function Page2({ pageTitleRef }) { return ( <div className="Page2"> {createPortal("Page1 title", pageTitleRef.current)} <h2>Page 2 content!</h2> </div> ); }

sin embargo, arroja un error Target container is not a DOM element.

https://codesandbox.io/s/xenodochial-mendeleev-b5pbr?file=/src/App.js

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

0

El problema es que está tratando de usar pageTitleRef.current antes de que tenga algo. No tiene nada hasta que se procesa la App , pero durante la representación de la App , está intentando llamar a createPortal (desde la Page1 1 y Page2 ).

Tendrá que hacer algunas refactorizaciones; algunas opciones:

  1. Renderice normalmente en esa área, en lugar de que Page1 y Page2 se comuniquen con ella a través de createPortal ; La App ya sabe en qué página está.
  2. Coloque el área del portal en su esqueleto HTML, en lugar de representarlo con App .
  3. Mantenga el contenido que debería estar en el encabezado en el estado de la App y pase una función de establecimiento a la Page1 1 y Page2 que pueden usar para configurar ese contenido.

Iría con #1, Page1 y Page2 parecen tener demasiadas responsabilidades (encabezado de página y cuerpo de página). Puede dividirlos en PageHead1 / PageHead2 y PageBody1 / PageBody2 . Pero si tiene más sentido, el n.° 2 o el n.° 3 también podrían funcionar.

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!