Hola, soy nuevo en TypeScript y tengo trabajo que hacer aquí. Necesito hacer una clase dinámica, algo así como en este código a continuación.
import React, { ReactNode, useState } from "react"; interface Props { text: ReactNode; } const ListItem = ({ text }: Props) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> <div> <div className={`text ${showMore ? "active" : ""}`}>{text}</div> </div> <button onClick={() => setShowMore((s) => !s)}>Show more</button> </div> ); };Pero necesito implementarlo en este código y no tengo idea de cómo hacerlo, porque no entiendo esta sintaxis de alguien que la escribió. Cuando trato de implementar el código anterior, tengo un problema con la representación de ganchos de reacción en esta sintaxis.
Espero que entiendas mi problema
type DeliveryBranchHitProps = { hit: SearchIndex.DeliveryBranch; }; const DeliveryBranchHit = ({ hit: delivery_branch, }: DeliveryBranchHitProps): JSX.Element => ( <> <div className={`branch-opening-week ${showMore ? "active" : ""}`}> <p> <span className="branch-day">Monday:</span> {delivery_branch.opening_monday} </p> <button onClick={() => setShowMore((s) => !s)}>Show more</button> </div> </> );No estoy muy seguro de entender su pregunta, pero posiblemente quiera hacer algo como esto donde tiene un componente genérico que toma algo de contenido para chilren .
interface Props { text: ReactNode; children: ReactNode; } const ListItem = ({ text, children }: Props) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> <div> <div className={`text ${showMore ? "active" : ""}`}> {text} {children} </div> <button onClick={() => setShowMore((s) => !s)}>Show more</button> </div> </div> ); }; type DeliveryBranchHitProps = { hit: SearchIndex.DeliveryBranch; }; const DeliveryBranchHit = ({ hit: delivery_branch }: DeliveryBranchHitProps): JSX.Element => ( <> <ListItem text={delivery_branch.name} /> <p> <span className="branch-day">Monday:</span> {delivery_branch.opening_monday} </p> </ListItem> </> );Consulte esta publicación para comprender const func = () => ( .. ) sintaxis Función de flecha sin llaves
Por ahora, su función devuelve una sola expresión, es decir, algo de JSX. Para agregar algo de lógica adicional, debe hacer que su función sea multilínea (preste atención a las llaves):
const Func = (props) => { // your hook goes here let [state, useState] = useState(); // return the jsx return ( .. ) }UPD: entonces para tu caso es:
type DeliveryBranchHitProps = { hit: SearchIndex.DeliveryBranch; }; const DeliveryBranchHit = ({ hit: delivery_branch, }: DeliveryBranchHitProps): JSX.Element => { let [showMore, setShowMore] = useState(false); return ( <> <div className={`branch-opening-week ${showMore ? "active" : ""}`}> <p> <span className="branch-day">Monday:</span> {delivery_branch.opening_monday} </p> <button onClick={() => setShowMore((s) => !s)}>Show more</button> </div> </> ); }