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

277
Views
React.js cómo obtener un elemento y pintarlo de un color diferente

Estoy creando una aplicación de cine, donde seleccionaré asientos en la sala de cine y agregaré boletos al carrito

Función para mostrar la sala de cine:

 export default function CinemaHall(props) { const row = props.row; const seats = props.seats; const hall = []; const [isActive, setIsActive] = useState(false); function getSeats(place) { setIsActive(isActive => !isActive); console.log("Row: " + row, "Place: " + place); } for(let i = 1; i < seats; i++) { hall.push( <div className="seats" onClick={() => getSeats(i)} style={{backgroundColor: isActive ? "rgb(255, 208, 0)" : "rgb(58, 130, 218)"}}></div> ) } return hall; }

Me devuelve el hall (ver imagen):

ingrese la descripción de la imagen aquí

Pero si hago clic en el asiento, no se vuelve a pintar un asiento, sino una fila completa. ¿Como arreglarlo?

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

0

Hay algunas cosas, pero la principal es que deberá mantener una bandera "activa" separada para cada asiento. Por ejemplo, podría tener un Set de asientos activos.

Ver comentarios para más detalles y otras notas:

 export default function CinemaHall({ row, seats }) { // Maintain a map of the seats that are "active" const [seatsActive, setSeatsActive] = useState(new Set()); function toggleSeat(place) { // Generally, use the callback form when updating state based on // existing state setSeatsActive((previous) => { // Get a new set const update = new Set(previous); // Toggle this seat: remove it if it's in the set, add it if // it isn't if (update.has(place)) { update.delete(place); } else { update.add(place); } console.log(`Row: ${row} Place: ${place} Active: ${update.has(place)}`); return update; }); } const hall = []; // If the first seat is `1`, you want to loop until `<= seats`, not // just `< seats`, if you want `seats` number of seats for (let seat = 1; seat <= seats; seat++) { // Note the `key` prop -- it's important to include that in arrays // managed by React. In this case, we can use the seat number, but // beware there are many times you can't use an array index as a key! // Note using `seatsActive.has(seat)` to see if the seat is "active" hall.push( <div key={seat} className="seats" onClick={() => toggleSeat(seat)} style={{ backgroundColor: seatsActive.has(seat) ? "rgb(255, 208, 0)" : "rgb(58, 130, 218)" }} /> // Note that in JSX (unlike HTML), you can self-close void // element tags like `div` ); } return hall; }

Remítase a mi nota sobre el uso del seat como clave: está bien aquí, pero generalmente no está bien usar un contador de bucle, los detalles en este artículo están vinculados a la documentación de las claves React .


Nota al margen: usaría una clase, no un estilo en línea, para indicar asientos activos:

 <div // ... className={`seat ${seatsActive.has(seat) ? "active" : ""}`} />
about 4 years ago · Juan Pablo Isaza Report

0

El principal problema es que tienes un estado para todos los lugares. Puedes hacer algo como esto. Y en mi opinión tienes una variable innecesaria como un salón.

 const CinemaHall = ({ seats = [1, 2, 3, 4, 5] }) => { const [seatsWithStatus, setSeatsWithStatus] = useState(() => { return seats.map((seat, idx) => ( { id: idx, // just in case seat, isActive: false } ) ) }); const getSeats = (id) => { const foundSeat = seatsWithStatus.find(seat => seat.id === id); foundSeat.isActive = !foundSeat.isActive; setSeatsWithStatus(seatsWithStatus.map(seat => { if (seat.id === id) { return foundSeat; } return seat })) } const showSeatsElement = () => ( seatsWithStatus.map((seat, idx) => ( <div className="seats" key={idx} onClick={() => getSeats(seat.id)} style={{ backgroundColor: seat.isActive ? "rgb(255, 208, 0)" : "rgb(58, 130, 218)"}} ></div> )) ) return ( <> {showSeatsElement()} </> ) } export default CinemaHall;
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!