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

176
Views
¿Puedes usar una constante en lugar de la ruta del módulo cuando usas '"importar obj from "../modulePath"'? (Reaccionar)

Me gustaría importar una matriz llamada "contenido" de uno de varios archivos diferentes. Me gustaría establecer de qué módulo extraer en función de una const que creo (pageName), que titula la página en el componente PageTitle. Concatenaré esto a "modulePath" que se encuentra en un directorio fuera de mi carpeta de componentes. Pero tengo problemas para importar contenido cuando hago referencia a la ruta del módulo como una constante.

 import React from "react" import PageTitle from "./PageTitle" import BuildItems from "./BuildItems" function camelize(str) { return str.replace(/(?:^\w|[AZ]|\b\w|\s+)/g, function (match, index) { if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces return index === 0 ? match.toLowerCase() : match.toUpperCase(); }); } const pageName = "Settings"; const modulePath = "../" + camelize(pageName); import content from modulePath; function View() { return ( <div className="View"> <PageTitle content={pageName} layout="mini" /> {content.map(BuildItems)} </div> ); } export default View;

La estructura de la carpeta src es la siguiente:

 src/ components/ App.js BuildItems.js PageTitle.js View.js index.js settings.js

Funciona bien cuando reemplazo import content from modulePath con el import content from "../settings" . Pero deseo hacer esto dinámicamente cambiando el nombre de página const a cualquier otra cosa (esencialmente cambiando el contenido).

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Las importaciones de nivel superior deben ser cadenas estáticas conocidas en tiempo de compilación. Para su caso de uso, debe usar una importación dinámica en su lugar ( await import(...) ):

 import React from "react" import PageTitle from "./PageTitle" import BuildItems from "./BuildItems" function camelize(str) { return str.replace(/(?:^\w|[AZ]|\b\w|\s+)/g, function (match, index) { if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces return index === 0 ? match.toLowerCase() : match.toUpperCase(); }); } const pageName = "Settings"; const modulePath = "../" + camelize(pageName); function View() { const [content, setContent] = useState(null); useEffect(() => { (async () => { // using the `await import(modulePath)` syntax to import a path based on a variable setContent(await import(modulePath)) })(); }, []) if (content === null) { return <div>Loading...</div> } function load() { <PageTitle content={pageName} layout="mini" /> return content.map(BuildItems); } return ( <div className="View"> {load()} </div> ); } export default View;
about 4 years ago · Santiago Gelvez 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!