如何使用React Hooks更改按钮单击时的图像?

时间:2019-08-06 14:51:15

标签: reactjs react-hooks

我正在学习React,我想创建两个按钮:白色和黑色,将图像更改为白色T恤和黑色T恤。

我的目标是使用React Hooks实现这一目标。

import React, { useState, useEffect } from "react";
// import Black from "../../assets/black.jpg";
// import White from "../../assets/white.jpg";
import "./Shirts.css";

function Shirts() {
  const [white, setWhite] = useState(false);
  const [black, setBlack] = useState(true);

  const whiteImage = require(`../../assets/white.jpg`);
  const blackImage = require(`../../assets/black.jpg`);

  function changeToWhite() {
    console.log(setWhite(whiteImage));
  }

  function changeToBlack() {
    console.log(setBlack(blackImage));
  }

  // useEffect(() => {
  //   setWhite(white);
  // }, white);

  return (
    <div>
      <div className="Shirts">
        <img alt="T-Shirt" className="White" src={white} />
        <img alt="T-Shirt" className="Black" src={black} />
      </div>
      <div className="ColorPicker">
        <button className="WhiteB" onClick={changeToWhite}>
          <p className="WhiteT">
            W<br />
            H<br />
            I<br />
            T<br />E
          </p>
        </button>
        <button className="BlackB" onClick={changeToBlack}>
          <p className="BlackT">
            B<br />
            L<br />
            A<br />
            C<br />K
          </p>
        </button>
      </div>
    </div>
  );
}

export default Shirts;

我实现的是他们在第一次点击时就加载了,但随后又停止了工作。

1 个答案:

答案 0 :(得分:1)

首先导入两个图像:

const white = require('./images/white.png')
const black = require('./images/black.png')
const shirts = { white, black }

现在将selected T恤衫绑定到州的财产,并将其作为src传递:

const Shirts = () =>{
    const [selected, setSelected] = useState(shirts.white)

   return(
       <>
           <img src={selected} alt='shirt' />
           <button onClick={() => setSelected(shirts.black)}> Click</button>
       </>
   )
}