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

245
Views
¿Por qué mi imagen de fondo no cambia al hacer clic?

estoy haciendo un proyecto de reacción, y en mi proyecto hay una funcionalidad que cambia las imágenes de fondo al hacer clic, pero la imagen no se muestra. Algo cambia, pero la imagen no se muestra. Y estoy seguro de que tengo el camino correcto. Agradecería alguna idea. Gracias de antemano. Aquí está el código:

 export function theme_switcher(){ let value = true; let btn_theme_switcher = document.getElementById("theme-switcher"); function toggle(){ if(value){ black_theme(); value = false; } else { white_theme(); value = true; } } btn_theme_switcher.addEventListener("click", () => { toggle(); }) } function white_theme(){ console.log("white"); document.getElementById("background-img").style.backgroundImage = 'url("../images/bg-mobile-dark.jpg")'; document.getElementById("background-img").style.backgroundPosition = "center"; document.getElementById("background-img").style.backgroundSize = "cover"; } function black_theme(){ console.log("black"); document.getElementById("background-img").style.backgroundImage = 'url("../images/bg-mobile-dark.jpg")'; document.getElementById("background-img").style.backgroundPosition = "center"; document.getElementById("background-img").style.backgroundSize = "cover"; }

Esto está en otro archivo:

 export default function ReactUseEffect(){ React.useEffect(() => { theme_switcher(); default_task_counter(); delete_listener(); completed_listener(); }); return(null); }

Aquí está la versión en vivo: https://todo-list-lac-ten.vercel.app/ Aquí está mi github: https://github.com/OrlandoVSilva/todo-list.git

*Olvidé decirte dónde hacer clic. Está en el icono de la luna. ¡Lo siento!

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

0

Eso es principalmente porque usaste el value como una variable. Debe usar useEffect para manejar los estados de los componentes. Pero tal efecto también se puede lograr usando css

JS:

 function ThemeSwitcher() { const [dark, setDark] = useState(false); return ( <div className='...' > <div className={`bg${dark ? ' bg--dark' : ''}`} /> </div> ); }

CSS:

 .bg { background-position: center; background-size: cover; background-image: url("../images/bg-mobile-white.jpg"); } .bg.bg--dark { background-image: url("../images/bg-mobile-dark.jpg"); }

Además, mientras usas React, deberías olvidarte de métodos como getElementbyId o addEventListener , ya que tiene mejores soluciones para esto.

about 4 years ago · Juan Pablo Isaza Report

0

theme_switcher se llama a través React.useEffect pero creo que las devoluciones de llamada también deberían llamarse a través de React.useEffect , en lugar de llamar a black_theme(); , intenta llamar a React.useEffect(black_theme);
Además, todo esto probablemente esté en contra de todas las prácticas comunes de React.
Incluso si digamos que background-img está de alguna manera fuera del alcance de React (lo que sea que esto signifique), entonces al menos el value debería ser una variable de estado

about 4 years ago · Juan Pablo Isaza Report

0

Agradezco MUCHO la ayuda, pero logré dejar de trabajar con esto:

 import backgroundPic from "../images/bg-mobile-dark.jpg" //----------------------------------------------- export default function ContentHeaders(){ const change_theme = () => { let background = document.getElementById("background") background.style.backgroundImage = `url(${backgroundPic})` } return( <div id = "header"> <h1>TODO</h1> <div id = "theme-switcher" onClick = {change_theme}></div> </div> ); }
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!