我正在学习 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;
我实现的是它们在第一次单击时加载,但随后它们停止工作。
首先导入两个图像:
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>
</>
)
}