为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕虎7371278 2021-11-12 10:50:01
我不知道我应该怎么做才能在每次单击按钮时修改图像(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;
查看完整描述

1 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

您将此作为道具传递给您的 parent likeIcon ={likes.like1},它不会改变,因为它始终是静态的。您需要通过检查状态来确保传递正确的like值this.state.likeIcon


在父组件的渲染方法中,您传递的LikeIcon始终设置为likes.like1。


所以改变道具以反映最新的图标:


likeIcon={this.state.likeIcon ? likes.like2 : likes.like1}

见下文:


render() {

    return (

      <div className="dados">

        <InstaF4

          imagemUser={usuario.imagemUser}

          userName={usuario.userName}

          fotoPrincipal={fotoPrincipal.fotoPrincipal}


          // This should set the likeIcon as per the boolean variable

          likeIcon={this.state.likeIcon ? likes.like2 : likes.like1}


          commentIcon={likes.comment}

          curtida={this.botaoCurtido} />

      </div>

    );

}


查看完整回答
反对 回复 2021-11-12
  • 1 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信