【问题标题】:Trying to change my image - ADD to ADDED when onclick on the img, no idea how to go about it. I am new to React试图改变我的形象 - 当点击 img 时添加到添加,不知道如何去做。我是 React 的新手
【发布时间】:2022-11-23 08:12:17
【问题描述】:
import React, { useState } from 'react';
import NavBar from "../../components/navBar/navbar";
import "./profile.scss"
import add from './Images/add.png'
import added from './Images/added.png'

    
const Profile = () => {

    return (

    <div className="navbar-display">

        <NavBar/>

                                <div className="right" >
                                <img id='imageid' src={add} alt='' onClick={''}/>
                                </div>
           



    </div>
    )
}

export default Profile;
                                <div className="right" >
                                <img id='imageid' src={add} alt='' onClick={''}/>
                                
                                </div>

这是我遇到麻烦的部分。我尝试了很多在线方法,但经常遇到错误,似乎无法找到一种确定的方法来使用 ReactJS 单击更改图像

【问题讨论】:

    标签: reactjs react-native image react-hooks onclick


    【解决方案1】:

    只需简单地使用useState 来跟踪您的图像,就像这样:

    import React, { useState } from "react";
    import NavBar from "../../components/navBar/navbar";
    import "./profile.scss";
    import add from "./Images/add.png";
    import added from "./Images/added.png";
    
    const Profile = () => {
      const [image, setImage] = useState("left");
    
      const handleClick = () => {
        if (image === "left") {
          setImage("right");
        } else {
          setImage("left");
        }
      };
    
      return (
        <div className="navbar-display">
          <NavBar />
    
          <div className="right">
            <img
              id="imageid"
              src={image === "left" ? add : added}
              alt=""
              onClick={() => handleClick()}
            />
          </div>
        </div>
      );
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-01
      • 2021-09-27
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多