无法更改图标图像(反应)

我不知道我应该怎么做才能在每次单击按钮时修改图像(favorite.svg 和 favorite-white.sgv)。我更努力了,这很难。我使用反应。


每次单击按钮时,我都希望图像从 favourite-white.sgv 更改为 favourite.sgv(也将 favourite.sgv 更改为 favourite-white.sgv)。我不知道该怎么办,或者我做错了什么。


import React from 'react';

import logo from './logo.svg';

import './App.css'

import { InstaF4 } from './componentes/card.js';


const usuario = {

  imagemUser: require ('./componentes/img1.jpg'),

  userName: "Caroline"

}


const fotoPrincipal= {

  fotoPrincipal: 'https://picsum.photos/350/290?'

}


const likes = {

  like1: require ('./componentes/icones/favorite-white.svg'),

  like2:require ('./componentes/icones/favorite.svg'),

  comment: require ('./componentes/icones/comment_icon.svg'),

}



class App extends React.Component{

  constructor(props){

      super(props);

      this.state = {

      likeIcon: false,

      };

  }  


botaoCurtido = () =>{

  const semLike = this.state.likeIcon;

  this.setState ({likeIcon : !this.state.likeIcon})

};


/*botaoCurtido = () =>{

  const curtida = likes.like2

  this.setState ({likeIcon : curtida})

  //console.log ("testei")

};*/


render() {

  let likeIcon="";

  const curtida = likes.like2

  //let iconeCurtido = require ('./componentes/icones/favorite.svg');


  if(this.state.likeIcon === true){

    likeIcon = curtida

    console.log ("testeiiii")

    }


  return (

  <div className="dados">

    <InstaF4

    imagemUser={usuario.imagemUser}

    userName = {usuario.userName}


    fotoPrincipal={fotoPrincipal.fotoPrincipal}


    likeIcon = {likes.like1}

    likeIconLiked = {likes.like2}

    commentIcon = {likes.comment}

    curtida = {this.botaoCurtido}


    />


{likeIcon}

  </div>

   ) 

}


}



export default App;


慕虎7371278
浏览 134回答 1
1回答

陪伴而非守候

您将此作为道具传递给您的 parent likeIcon ={likes.like1},它不会改变,因为它始终是静态的。您需要通过检查状态来确保传递正确的like值this.state.likeIcon在父组件的渲染方法中,您传递的LikeIcon始终设置为likes.like1。所以改变道具以反映最新的图标:likeIcon={this.state.likeIcon ? likes.like2 : likes.like1}见下文:render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className="dados">&nbsp; &nbsp; &nbsp; &nbsp; <InstaF4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imagemUser={usuario.imagemUser}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userName={usuario.userName}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fotoPrincipal={fotoPrincipal.fotoPrincipal}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // This should set the likeIcon as per the boolean variable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; likeIcon={this.state.likeIcon ? likes.like2 : likes.like1}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; commentIcon={likes.comment}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; curtida={this.botaoCurtido} />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript