最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change image on click - React - Stack Overflow

programmeradmin9浏览0评论

So for example this is my view:

<div>
  <img src='../../minus.png' />
</div>

Now I want to make that on each click the image changes from plus.png to minus.png.

So, click once: minus.png => plus.png, click again: plus.png => minus.png, and so on. How can I make this?

So for example this is my view:

<div>
  <img src='../../minus.png' />
</div>

Now I want to make that on each click the image changes from plus.png to minus.png.

So, click once: minus.png => plus.png, click again: plus.png => minus.png, and so on. How can I make this?

Share Improve this question edited Jul 23, 2018 at 17:42 asked Jul 23, 2018 at 14:12 user8608046user8608046 3
  • 2 Post the code you already tried and we will fix it – Dmitrii G. Commented Jul 23, 2018 at 14:14
  • I haven't tried anything.. really newbie in React :(( Sorry.. :(( – user8608046 Commented Jul 23, 2018 at 14:15
  • You can't, it seems others can. :) – user8608046 Commented Jul 28, 2018 at 9:50
Add a ment  | 

4 Answers 4

Reset to default 12

This can be achieved with a simple toggle handler:

const imagesPath = {
  minus: "https://images.vexels./media/users/3/131484/isolated/preview/a432fa4062ed3d68771db7c1d65ee885-minus-inside-circle-icon-by-vexels.png",
  plus: "https://cdn3.iconfinder./data/icons/glypho-generic-icons/64/plus-big-512.png"
}

class App extends React.Component {
  state = {
    open: true
  }
  toggleImage = () => {
    this.setState(state => ({ open: !state.open }))
  }

  getImageName = () => this.state.open ? 'plus' : 'minus'

  render() {
    const imageName = this.getImageName();
    return (
      <div>
        <img style={{maxWidth: '50px'}} src={imagesPath[imageName]} onClick={this.toggleImage} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Edit
Note that I passed a function parameter for setState because my new state depends on the old state. You can read more about it in the docs

Try this sample code on button click change the condition to render the img src:

    import React from "react";
import "./styles.css";
import { Card, CardImg, CardBody, Button } from "reactstrap";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      loginState: true
    };
  }

  render() {
    let sessonState;
    let imgurl;
    if (this.state.loginState) {
      sessonState = "Logged In";
      imgurl = "https://picsum.photos/id/237/200/300";
    } else {
      imgurl = "https://picsum.photos/seed/picsum/200/300";
      sessonState = "Logged Out";
    }

    return (
      <div>
        <h1>Session {sessonState}!!</h1>
        <br />
        <div className="container">
          <div className="row">
            <div className="col-md-4">
              <Card className="shadow">
                <CardImg top width="100%" src={imgurl} alt="Card image cap" />
                <CardBody>
                  <Button
                    className="shadow-sm btn "
                    onClick={() => {
                      this.setState({
                        loginState: false
                      });
                      console.log(`${imgurl}`);
                    }}
                  >
                    Button
                  </Button>
                </CardBody>
              </Card>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default App;
import React, { useState } from 'react';
import './Bulbs.css';

function Bulb(){

    const bulboff = require('../assets/BulbOff.png');
    const bulbon = require('../assets/BulbOn.png');
    const images = {bulboff,bulbon};
    const [img, setImg] = useState(false);

    const imgChangeHandler = () => {
        if(!img) {
            setImg(true);
        }else{
            setImg(false)
        }
    };
    return(
        <div>
            <img src={!img ? bulboff : bulbon } alt='bulb-off' onClick={imgChangeHandler}/>
        </div>
    )
}


export default Bulb;

Assuming this is inside the render function:

<div>
  <img onClick={() => {this.setState({clicked: true})} 
       src={'../../' + (this.state.clicked ? 'plus' : 'minus') + '.png'}} />
</div>
发布评论

评论列表(0)

  1. 暂无评论