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

190
Views
Quiero que la imagen cambie cuando hago clic en el botón en el componente de clase React JS

Quiero que la imagen cambie cuando hago clic en el botón en el componente de clase. Conozco el componente de función, pero ¿cómo puedo hacer esto?

 class Coffies extends React.Component{ constructor(props){ super(props) this.state={ giphy:[], loading:false } } componentDidMount(){ const apiURL = "https://api.giphy.com/v1/gifs/random"; const apiKEY = "bi3FFnNepwMz5HlDYwCfvyhXQLGrvVtL"; const randomIndex = Math.floor(Math.random()*50); axios(`${apiURL}?api_key=${apiKEY}`) .then((response)=> this.setState({ giphy : response.data.data.images.fixed_height.url, loading: true })) } render(){ return ( <> <img className="cats-img" src={this.state.giphy} alt="Loading.." /> <button onClick={()=> this.setState({loading : false})} className="mt-5 py-3 btn generate-btn"> Get Random Cat Images </button> </> ) } } export default Coffies ;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede cambiar la imagen al hacer clic en el botón, si crea un método changeImage

 changeImage = () => { this.setState({ loading: true, }); this.getImage(); };

Demo en vivo

Demostración de Codesandbox

y llame al método getImage en él

 getImage() { const apiURL = "https://api.giphy.com/v1/gifs/random"; const apiKEY = "bi3FFnNepwMz5HlDYwCfvyhXQLGrvVtL"; axios(`${apiURL}?api_key=${apiKEY}`).then((response) => { this.setState({ giphy: response.data.data.images.fixed_height.url, loading: false, }); }); }
about 4 years ago · Juan Pablo Isaza Report

0

ComponentDidMount() solo se ejecuta una vez en general, por lo que no es un buen lugar para poner la lógica de carga de la imagen. Debe colocar su lógica dentro de un controlador onClick:

 <button onClick={changeImage} className="mt-5 py-3 btn generate-btn">Get Random Cat Images</button>

que luego llama a la función sugerida por @decpk

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!