Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
¿Cómo pasar el componente como accesorio y renderizarlo condicionalmente?

Tengo un componente aquí que obtiene un número de identificación y verifica si ese número de identificación existe en la base de datos. Si existe, debería representar un componente y, de lo contrario, mostrar un mensaje de error. Luchando con cómo debería escribirlo, cualquier ayuda es apreciada.

 function PatientIDInput({component}) { const [patientID, setPatientID] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const [showComponent, setShowComponent] = useState(false); const [patientInformation, setPatientInformation] = useState(''); const handleChange = (e) => { // some input change handling } const handleSubmit = (e) => { e.preventDefault(); Physician.fetchPatientData(patientID) .then(res => { if (res.status === 200) { // show component if patient exists } }) .catch(error => { if (error.response.status) { // set error if not } }) } return ( <> <form onSubmit={handleSubmit}> // some UI code for user's input </form> { showComponent ? {Component patientInformation={patientInformation}} /> // this is where I'm struggling with the syntax. How should I write the logic? I want to pass some props to the component too. : null} </> ); } export default PatientIDInput;
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Aquí hay algunos patrones que usé con más frecuencia.

Pasar un "Componente Reaccionar"

 function PatientIDInput({Component}) { // skip return ( <> <form onSubmit={handleSubmit}> // some UI code for user's input </form> { showComponent ? <Component patientInformation={patientInformation} /> : null} </> ); } export default PatientIDInput;
 const Sample = ({ patientInformation }) => <div>{patientInformation}</div> <PatientIDInput Component={Sample} />

Pasar una "Función de renderizado" como niños

 function PatientIDInput({children}) { // skip return ( <> <form onSubmit={handleSubmit}> // some UI code for user's input </form> { showComponent ? children({ patientInformation }) : null} </> ); } export default PatientIDInput;
 const Sample = ({ patientInformation }) => <div>{patientInformation}</div> <PatientIDInput> {({ patientInformation }) => <Sample patientInformation ={patientInformation} />} </PatientIDInput>

Pasar un "Elemento Reaccionar" como niños

 function PatientIDInput({children}) { // skip return ( <> <form onSubmit={handleSubmit}> // some UI code for user's input </form> { showComponent ? React.cloneElement(children, { patientInformation }) : null} </> ); } export default PatientIDInput;
 const Sample = ({ patientInformation }) => <div>{patientInformation}</div> <PatientIDInput> <Sample/> </PatientIDInput>
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puedes usar

 React.cloneElement( element, [config], [...children] )

Clone y devuelva un nuevo elemento React usando el elemento como punto de partida. config debe contener todos los accesorios, claves o referencias nuevos. El elemento resultante tendrá los accesorios del elemento original con los accesorios nuevos fusionados superficialmente. Los niños nuevos reemplazarán a los niños existentes. La clave y la referencia del elemento original se conservarán si no hay ninguna clave ni referencia en la configuración.

Ejemplo

 import React from "react"; function Child(props) { return <div>{props.name}</div>; } function SomeOtherComponent(props) { return ( <> {React.cloneElement(props.component, { someFunction: () => { console.log("inside callback"); }, name: "Ganesh", })} </> ); } function App() { return ( <div> Hi <SomeOtherComponent component={<Child />}></SomeOtherComponent> </div> ); }
about 4 years ago · Juan Pablo Isaza Denunciar

0

En lugar de pasar el componente como accesorios, importe el componente directamente dentro del componente PatientIdInput y pase la información del paciente como accesorios de esta manera:

 **Import your Component Here** function PatientIDInput({component}) { const [patientID, setPatientID] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const [showComponent, setShowComponent] = useState(false); const [patientInformation, setPatientInformation] = useState('');

En la parte de regreso:

 return ( <> <form onSubmit={handleSubmit}> // some UI code for user's input </form> { showComponent ? <ImportedComponent patientInformation={patientInformation}/> : null} </> ); } export default PatientIDInput;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda